#include "mymodbus.h"
#include <QSerialPortInfo>
#include <QSerialPort>
#include <QSqlQuery>
#include <QVariant>
#include <QSqlError>
#include <QModbusDevice>
#include <QDebug>
#include <QModbusRtuSerialMaster>
#include <qmath.h>
#include <QEventLoop>
#include <QByteArray>
#include <QElapsedTimer>
#include <QCoreApplication>
#include <QtConcurrent/QtConcurrent>
#include <QThread>
#include <QtGlobal>
#include <QJsonObject> // { }
#include <QJsonDocument> // 解析Json
#include <QJsonValue> // int float double bool null { } [ ]
#include <QJsonParseError>
#include <QUuid>
#include <QMatrix>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTextCodec>
#include <private/qzipwriter_p.h>
#include <private/qzipreader_p.h>
#include <exception>
#include <malloc.h>
#include <QMutexLocker>
#include <QProcess>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>

//using namespace QtConcurrent;
#define RW_REG_COUNT_DIR_0 7 //通道1计数方向：占1寄存器
#define RW_REG_COUNT_DIR_1 8 //通道2计数方向：占1寄存器
#define RW_REG_COUNT_DIR_2 9 //通道3计数方向：占1寄存器
#define RW_REG_POS_ACT_0 10 //通道1编码器数据：占2寄存器
#define RW_REG_POS_ACT_1 12 //通道2编码器数据：占2寄存器
#define RW_REG_POS_ACT_2 14 //通道3编码器数据：占2寄存器
#define RW_REG_FILTER_LEVEL_0 16 //通道1输入滤波：占1寄存器
#define RW_REG_FILTER_LEVEL_1 17 //通道2输入滤波：占1寄存器
#define RW_REG_FILTER_LEVEL_2 18 //通道3输入滤波：占1寄存器

#define PWM_PHYS_BASE  0x01c21000 
#define PWM_REG_SIZE   0x1000
#define PWM_REG_OFFSET 0x400

#define DEV_MEM_PATH    "/dev/mem"  // Linux下用于内存映射的设备文件 

#define DEBUG_4G        0
#define DEBUG_GPS       0
#define DEBUGMODBUS     0

#define GPS_4G_IS_ONE   0

QAtomicInteger<bool>  change4gport(false);
QAtomicInteger<bool>  reconnect4g(false);
QAtomicInteger<bool>  busyflag4g(false);
QAtomicInteger<bool>  otaresult(false);
QAtomicInteger<bool>  m_continueSend(false);
QAtomicInteger<bool>  m_get4gSignal(false);
QAtomicInteger<bool>  m_getclk(false);
QAtomicInteger<bool>  m_cpin(false);
QAtomicInteger<bool>  m_openMqttClient(false);
QAtomicInteger<bool>  m_connectMqttClient(false);
QAtomicInteger<bool>  m_cgreg(false);
QAtomicInteger<bool>  pub(false);
QAtomicInteger<bool>  m_subSuccess(false);
QAtomicInteger<bool>  getGPS(false);
QAtomicInteger<bool>  m_error_response(false);

volatile uint32_t* pwm_map_registers(uint32_t phys_base, size_t reg_size) {
    int fd;
    volatile uint32_t* virt_addr;
    uint32_t page_size = sysconf(_SC_PAGESIZE);
    uint32_t page_mask = page_size - 1;
    uint32_t aligned_phys_base = phys_base & ~page_mask;
    uint32_t offset = phys_base - aligned_phys_base;
    size_t aligned_reg_size = ((reg_size + offset + page_mask) & ~page_mask);

    // 打开/dev/mem（需root权限，否则失败）
    fd = open(DEV_MEM_PATH, O_RDWR | O_SYNC);  // O_SYNC：禁止缓存，确保写入立即生效
    if (fd < 0) {
        return NULL;
    }
    // 内存映射：将物理地址[phys_base, phys_base+reg_size)映射到虚拟地址
    virt_addr = (volatile uint32_t*)mmap(
        NULL,                   // 让系统自动分配虚拟地址起始位置
        aligned_reg_size,               // 映射的内存大小
        PROT_READ | PROT_WRITE, // 权限：可读可写
        MAP_SHARED,             // 共享映射（其他进程可见）
        fd,                     // 关联的/dev/mem文件描述符
        aligned_phys_base       // 要映射的物理地址（必须是页对齐的，通常硬件基地址已满足）
    );
    // 关闭文件描述符（映射后不再需要，但虚拟地址仍有效）
    close(fd);

    // 检查映射是否成功
    if (virt_addr == MAP_FAILED) {
        return NULL;
    }

    return virt_addr;
}

int pwm_set(volatile uint32_t* virt_base) {
    if (virt_base == NULL) {
        return -1;
    }
    *virt_base = (*virt_base) | 0x50;  // 设置特定值
    return 0;
}
void pwm_unmap(volatile uint32_t* virt_addr, size_t reg_size) {
    if (virt_addr != NULL && virt_addr != MAP_FAILED) {
        munmap((void*)virt_addr, reg_size);
    }
}

MyModBus::MyModBus(QObject* parent)
    : QObject(parent)
    ,m_db(QSqlDatabase::database("qt_sql_default_connection"))
    ,m_query(new QSqlQuery(m_db))
{
    getData();
    setbacklightvalue(m_backlight);
    connect(this,&MyModBus::backlightChanged,this,&MyModBus::slotbacklightChanged);
    setVersionAndDevTime("1.0.0", "2025-03-11");
    modbusDevice = new QModbusRtuSerialMaster(this);
    refreshComParas();
    pPrinter= new MyPrinter();
    pPrinter->Printer_init(m_comName);
    connectSerialPort();

    powerMode(true);
    timer = new QTimer(this);
    timer->setInterval(m_collectTime);
    connect(timer,SIGNAL(timeout()),this,SLOT(onTimeOut()));        //哦哦
    timer->start();     //哦哦 开启定时器了。
    connect(this,&MyModBus::collectTimeChanged,this,&MyModBus::slotCollectTimeChanged); //哦哦 重新配置 采集定时器。
    timerbeep = new QTimer(this);
    timerbeep->setInterval(50);
    timerbeep->setTimerType(Qt::PreciseTimer); // 设置为高精度定时器
    timerbeep->setSingleShot(true); // 设置为单次触发
    connect(timerbeep,SIGNAL(timeout()),this,SLOT(BeepTimeOut()));
    setCurrentMode(0);  //哦哦 正常模式，非“累加模式”。
    QtConcurrent::run(this,&MyModBus::sendDataBy4g);
}

MyModBus::~MyModBus()
{

    isClosed = true;
    if(!modbusDevice)
    {
        modbusDevice->disconnectDevice();
        delete modbusDevice;
        modbusDevice = nullptr;
    }
    if(!m_query)
    {
        delete m_query;
        m_query = nullptr;
    }
    timer->stop();
    delete timer;
    timer = nullptr;
    if(serialPort4g)
    {
        disconnect(serialPort4g,SIGNAL(readyRead()),0,0);
        serialPort4g->clear();
        serialPort4g->close();        
        delete serialPort4g;
        serialPort4g = nullptr;
    }
//    timerEncoder->stop();
//    delete timerEncoder;
//    timerEncoder = nullptr;
//    if(!encoderModbusDevice)
//    {
//        encoderModbusDevice->disconnectDevice();
//        delete encoderModbusDevice;
//        encoderModbusDevice = nullptr;
//    }
//    if(!serialPort4g)
//    {
//        serialPort4g->close();
//        delete serialPort4g;
//        serialPort4g = nullptr;
    //    }
}

QVariantList MyModBus::weightDatas() const
{
    return m_weightDatas;
}

QString MyModBus::startTime()
{
    return m_startTime;
}

void MyModBus::setStartTime(QString startTime)
{
    m_startTime=startTime;
    //emit startTimeChanged();
}

QString MyModBus::endTime()
{
    return m_endTime;
}

void MyModBus::setEndTime(QString endTime)
{
    m_endTime = endTime;
    //emit endTimeChanged();
}

int MyModBus::currentPage()
{
    return m_currentPage;
}

void MyModBus::setCurrentPage(int currentPage)
{
    m_currentPage = currentPage;
    //emit currentPageChanged();
    loadWeightData();
}

int MyModBus::accumulateMode()
{
    return m_accumulateMode;
}

void MyModBus::setAccumulateMode(int accumulateMode)
{
    m_accumulateMode = accumulateMode;
    showSumWeight = false;
    emit accumulateModeChanged();
}

int MyModBus::currentMode()
{
    return m_currentMode;
}

void MyModBus::setCurrentMode(int currentMode)
{
    m_currentMode = currentMode;
    QDateTime dateTime0= QDateTime::currentDateTime();//获取系统当前的时间
    QString str0 = dateTime0.toString("yyyy-MM-dd hh:mm:ss");//格式化时间

    if(m_currentMode == 0)      //哦哦 正常模式。
    {
        showSumWeight = false;
        getWeight();
        saveWeight(str0, m_weight_new.toDouble(), m_unit, 5, 0);
    }
    else if(m_currentMode == 1) //哦哦 累加模式。
    {
        saveWeight(str0, m_weight_new.toDouble(), m_unit, 6, 0);
    }
    emit currentModeChanged();      //哦哦 没有对应的信号处理器。
}

double MyModBus::accumulateZero()
{
    return m_accumulateZero;
}

bool MyModBus::setAccumulateZero(double accumulateZero)
{
    //    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    //    db.setDatabaseName("mydatabase.db");
    //    if(!db.open())
    //    {
    //        return;
    //    }
    //    QSqlQuery* query = new QSqlQuery(db);
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET accumulateZero = %1 WHERE id = 1;")
                           .arg(accumulateZero);
    bool updated = m_query->exec(queryser);
    if(!updated){
        //db.close();
        m_query->lastError();
        m_query->finish();
        return result;
    }
    m_query->finish();
    //db.close();
    m_accumulateZero = accumulateZero;
    emit accumulateZeroChanged();
    result = true;
    return result;
}

int MyModBus::autoSave()
{
    return m_autoSave;
}

bool MyModBus::setAutoSave(int autoSave)
{
    //    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    //    db.setDatabaseName("mydatabase.db");
    //    if(!db.open())
    //    {
    //        return;
    //    }
    //    QSqlQuery* query = new QSqlQuery(db);
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET autoSave = %1 WHERE id = 1;")
                           .arg(autoSave);
    bool updated = m_query->exec(queryser);
    if(!updated){
        //db.close();
        m_query->lastError();
        m_query->finish();
        return result;
    }
    m_query->finish();
    //db.close();
    m_autoSave = autoSave;
    emit autoSaveChanged();
    result = true;
    return result;
}

int MyModBus::saveDays()
{
    return m_saveDays;
}

bool MyModBus::setSaveDays(int saveDays)
{
    //    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    //    db.setDatabaseName("mydatabase.db");
    //    if(!db.open())
    //    {
    //        return;
    //    }
    //    QSqlQuery* query = new QSqlQuery(db);
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET saveDays = %1 WHERE id = 1;")
                           .arg(saveDays);
    bool updated = m_query->exec(queryser);
    if(!updated){
        //db.close();
        m_query->lastError();
        m_query->finish();
        return result;
    }
    m_query->finish();
    //db.close();
    m_saveDays = saveDays;
    emit saveDaysChanged();
    result = true;
    return result;
}

bool MyModBus::init()
{
    return m_init;
}

bool MyModBus::setInit(bool init)
{
    m_init = init;
    emit initChanged(init);
    return true;
}

bool MyModBus::downloadOTAPackage()
{
    return m_downloadOTAPackage;
}

bool MyModBus::setDownloadOTAPackage(bool downloadOTAPackage)
{
    m_downloadOTAPackage = downloadOTAPackage;
    emit downloadOTAPackageChanged(m_downloadOTAPackage);
    return true;
}

QStringList MyModBus::comData()
{
    QStringList coms;
    foreach (const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        QSerialPort tempSer;
        tempSer.setPort(info);
        coms.append(tempSer.portName());
//        if(tempSer.open(QIODevice::ReadWrite))
//        {
//            coms.append(tempSer.portName());
//            tempSer.close();
//        }
    }
    m_comData = coms;
    return coms;
}
void MyModBus::refreshComParas()
{
    //QSqlDatabase db = QSqlDatabase::addDatabase(m_db);
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
    if(!m_db.isOpen())
    {
        m_db.open();
    }

    /*可以连接3种设备，但可能不会同时连接。
    */
    QString queryser= QString("select "
                               "dt45COM,    dt45Baudrate,     dt45DataBit,      dt45StopBit,    dt45Parity"
                               ",COM4g,     baudrate4g,       dataBit4g,        stopBit4g,      parity4g"
                               ",encoderCOM, encoderBaudrate, encoderDataBit,   encoderStopBit, encoderParity "
                               "from "
                               "configTable where id = 1");
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_comName=m_query->value(0).toString();
        m_baudrate=m_query->value(1).toInt();
        m_dataBit=m_query->value (2).toInt();
        m_stopBit=m_query->value(3).toInt();
        m_parity=m_query->value(4).toInt();

        m_comName4g=m_query->value(5).toString();
        m_baudrate4g=m_query->value(6).toInt();
        m_dataBit4g=m_query->value (7).toInt();
        m_stopBit4g=m_query->value(8).toInt();
        m_parity4g=m_query->value(9).toInt();

        m_comNameEncoder=m_query->value(10).toString();
        m_baudrateEncoder=m_query->value(11).toInt();
        m_dataBitEncoder=m_query->value (12).toInt();
        m_stopBitEncoder=m_query->value(13).toInt();
        m_parityEncoder=m_query->value(14).toInt();
    }
    m_query->finish();
    //db.close();
//    emit comNameChanged(m_comName);
//    emit baudrateChanged(m_baudrate);
//    emit dataBitChanged(m_dataBit);
//    emit stopBitChanged(m_stopBit);
//    emit parityChanged(m_parity);
}
QString MyModBus::comName()
{
    return m_comName;
}

QString MyModBus::qccid()
{
    return m_qccid;
}

bool MyModBus::cpin()
{
    return m_cpin;
}
int MyModBus::baudrate()
{
    return m_baudrate;
}
int MyModBus::dataBit()
{
    return m_dataBit;
}
int MyModBus::stopBit()
{
    return m_stopBit;
}
int MyModBus::parity()
{
    return m_parity;
}

QString MyModBus::comName4g()
{
    return m_comName4g;
}

int MyModBus::baudrate4g()
{
    return m_baudrate4g;
}

int MyModBus::dataBit4g()
{
    return m_dataBit4g;
}

int MyModBus::stopBit4g()
{
    return m_stopBit4g;
}

int MyModBus::parity4g()
{
    return m_parity4g;
}

QString MyModBus::comNameEncoder()
{
    return m_comNameEncoder;
}

int MyModBus::baudrateEncoder()
{
    return m_baudrateEncoder;
}

int MyModBus::dataBitEncoder()
{
    return m_dataBitEncoder;
}

int MyModBus::stopBitEncoder()
{
    return m_stopBitEncoder;
}

int MyModBus::parityEncoder()
{
    return m_parityEncoder;
}
bool MyModBus::slotSaveComParas(QString comName,int baudrate,int dataBit,int stopBit,int parity, int type)
{
    return saveComParas(comName,baudrate,dataBit,stopBit,parity,type);
}

bool MyModBus::slotSaveComParas_new(QString comName, int baudrate, int dataBit, int stopBit, int parity, int slaveID, int type)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser;
    if(type == 0)
    {
        queryser= QString("UPDATE configTable SET dt45COM = '%1', dt45Baudrate = %2, dt45DataBit = %3, dt45StopBit = %4, dt45Parity = %5, dt45SlaveId = %6 WHERE id = 1;")
                       .arg(comName)
                       .arg(baudrate)
                       .arg(dataBit)
                       .arg(stopBit)
                       .arg(parity)
                       .arg(slaveID);
        m_comName = comName;
        m_baudrate = baudrate;
        m_dataBit = dataBit;
        m_stopBit = stopBit;
        m_parity = parity;
        m_sensorSlaveID = slaveID;
    }
    else
    {
        queryser= QString("UPDATE configTable SET encoderCOM = '%1', encoderBaudrate = %2, encoderDataBit = %3, encoderStopBit = %4, encoderParity = %5, encoderSlaveId = %6 WHERE id = 1;")
                       .arg(comName)
                       .arg(baudrate)
                       .arg(dataBit)
                       .arg(stopBit)
                       .arg(parity)
                       .arg(slaveID);
        m_comNameEncoder = comName;
        m_baudrateEncoder = baudrate;
        m_dataBitEncoder = dataBit;
        m_stopBitEncoder = stopBit;
        m_parityEncoder = parity;
        m_encoderSlaveID =slaveID;
    }
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();

    if(modbusDevice)
    {
        modbusDevice->disconnectDevice();
    }
    connectSerialPort();
//    if(type == 0)
//    {
//        if(modbusDevice)
//        {
//            modbusDevice->disconnectDevice();
//        }
//        connectSerialPort();
//    }
//    else
//    {
//        if(encoderModbusDevice)
//        {
//            encoderModbusDevice->disconnectDevice();
//        }
//        connectEncoder();
//    }
    result =true;
    return result;
}

bool MyModBus::slotSaveMqttParas(QString hostName, int port, QString topic, QString userName, QString password, int isOpen, QString truckNo, QString clientID, QString subTopic)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser;
    queryser= QString("UPDATE mqttTable SET hostName = '%1', port = %2, topic = '%3', userName = '%4', pwd = '%5', isOpen = %6, clientID = '%8', subTopic = '%9' WHERE id = 1;")
                   .arg(hostName)
                   .arg(port)
                   .arg(topic)
                   .arg(userName)
                   .arg(password)
                   .arg(isOpen)
                   .arg(clientID)
                   .arg(subTopic);
    m_hostName = hostName;
    m_port = port;
    m_topic = topic;
    m_userName = userName;
    m_password = password;
    m_mqttSwitch = isOpen;
    m_clientID = clientID;
    m_subTopic =subTopic;
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    bool updated2=setTruckNo(truckNo);
    if(!updated2)
    {
        return result;
    }
    m_query->finish();
    //db.close();
    result =true;
    return result;
}

bool MyModBus::slotSaveNormalPara(double upperUpperLimit, double upperLimit, double lowerLimit, double lowerLowerLimit, int collectTime, int saveInterval, double accumulateZero, int autoSave, int saveDays, int backlight, int screenSaveTime)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser;
    queryser= QString("UPDATE configTable SET upperLimit = '%1', upperUpperLimit = %2, lowerLimit = '%3', lowerLowerLimit = '%4', collectTime = '%5', saveInterval = %6, accumulateZero = %7, autoSave = %8, saveDays = %9, Backlight = %10, screenSaverTime = %11;")
                   .arg(upperLimit)
                   .arg(upperUpperLimit)
                   .arg(lowerLimit)
                   .arg(lowerLowerLimit)
                   .arg(collectTime)
                   .arg(saveInterval)
                   .arg(accumulateZero)
                   .arg(autoSave)
                   .arg(saveDays)
                   .arg(backlight)
                   .arg(screenSaveTime);
    m_upperLimit = upperLimit;
    m_upperUpperLimit = upperUpperLimit;
    m_lowerLimit = lowerLimit;
    m_lowerLowerLimit = lowerLowerLimit;
    m_collectTime = collectTime;
    m_saveInterval = saveInterval;
    m_accumulateZero = accumulateZero;
    m_autoSave = autoSave;
    m_saveDays = saveDays;
    m_backlight = backlight;
    m_screenSaveTime = screenSaveTime;
    emit collectTimeChanged(m_collectTime);
    emit backlightChanged(m_backlight);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    result =true;
    return result;
}

void MyModBus::getbacklight()
{
        if(!m_db.isOpen())
        {
            m_db.open();
        }

        QString queryser= QString("select "
                                   "Backlight "
                                   "from "
                                   "configTable where id = 1;");
        m_query->exec(queryser);
        if(m_query->next())
        {
            m_backlight = m_query->value(0).toInt();
            emit backlightChanged(m_backlight);
        }
        else
        {
            qDebug()<<m_query->lastError();
        }

        m_query->finish();
        //db.close();
}
void MyModBus::getScreenSaveTime()
{
        if(!m_db.isOpen())
        {
            m_db.open();
        }

        QString queryser= QString("select "
                                   "screenSaverTime "
                                   "from "
                                   "configTable where id = 1;");
        m_query->exec(queryser);
        if(m_query->next())
        {
            m_screenSaveTime = m_query->value(0).toInt();
        }
        else
        {
            qDebug()<<m_query->lastError();
        }

        m_query->finish();
        //db.close();
}


void MyModBus::getUnit()
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("select "
                               "unit "
                               "from "
                               "configTable where id = 1");
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_unit=m_query->value(0).toString();
    }
    m_query->finish();
    //db.close();
    emit unitChanged(m_unit);
}

void MyModBus::getUpperUpperLimit()
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("select "
                               "upperUpperLimit "
                               "from "
                               "configTable where id = 1");
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_upperUpperLimit=m_query->value(0).toFloat();
    }
    m_query->finish();
    //db.close();
    emit upperUpperLimitChanged(m_upperUpperLimit);
}

void MyModBus::getUpperLimit()
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("select "
                               "upperLimit "
                               "from "
                               "configTable where id = 1");
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_upperLimit=m_query->value(0).toFloat();
    }
    m_query->finish();
    //db.close();
    emit upperLimitChanged(m_upperLimit);
}

void MyModBus::getLowerLimit()
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("select "
                               "lowerLimit "
                               "from "
                               "configTable where id = 1");
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_lowerLimit=m_query->value(0).toFloat();
    }
    m_query->finish();
    //db.close();
    emit lowerLimitChanged(m_lowerLimit);
}

void MyModBus::getLowerLowerLimit()
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("select "
                               "lowerLowerLimit "
                               "from "
                               "configTable where id = 1");
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_lowerLowerLimit=m_query->value(0).toFloat();
    }
    m_query->finish();
    //db.close();
    emit lowerLowerLimitChanged(m_lowerLowerLimit);
}

void MyModBus::getSteadyStateFiltering()
{
    if(!modbusDevice)
    {
        return;
    }
    bool replyFinished=false;
    auto *reply = modbusDevice->sendReadRequest(readRequest(12, 1), m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
            //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadSteadyStateFiltering);
        } else {
            replyFinished=true;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        return;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 1)
            {
                m_steadyStateFiltering =unit.value(0);
                //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
                //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
                emit steadyStateFilteringChanged(m_steadyStateFiltering);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }

    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::getDigitalFiltering()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(11, 1), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadDigitalFiltering);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getSlaveID()
{//dt45SlaveId
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("select "
                               "addrs "
                               "from "
                               "configTable where id = 1");
    m_query->exec(queryser);
    if(m_query->next())
    {
        //m_slaveID=query->value(0).toInt();
        QString temp = m_query->value(0).toString();
        if(temp.length()>0){
            QStringList list = temp.split(",");
            m_slaveID = list.at(0).toInt();
        }
    }
    m_query->finish();
    //db.close();
    emit slaveIDChanged(m_slaveID);
}

void MyModBus::getStabilityRange()
{
    if(!modbusDevice)
    {
        return;
    }
    bool replyFinished=false;
    auto *reply = modbusDevice->sendReadRequest(readRequest(9, 1), m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
            //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadStabilityRange);
        } else {
            replyFinished=true;
            //delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        return;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 1)
            {
                m_stabilityRange =unit.value(0);
                //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
                //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
                emit stabilityRangeChanged(m_stabilityRange);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }

    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::getClearRange()
{
    if(!modbusDevice)
    {
        return;
    }
    bool replyFinished=false;
    auto *reply = modbusDevice->sendReadRequest(readRequest(10, 1), m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
            //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadClearRange);
        } else {
            replyFinished = true;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        return;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 1)
            {
                m_clearRange =unit.value(0);
                //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
                //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
                emit clearRangeChanged(m_clearRange);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }

    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::getPowerAutoZero()
{
    if(!modbusDevice)
    {
        return;
    }
    bool replyFinished=false;
    auto *reply = modbusDevice->sendReadRequest(readRequest(7, 1), m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
            //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPowerAutoZero);
        } else {
            replyFinished=true;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        return;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 1)
            {
                m_powerAutoZero =unit.value(0);
                //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
                //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
                emit powerAutoZeroChanged(m_powerAutoZero);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::getZeroTraceRange()
{
    if(!modbusDevice)
    {
        return;
    }
    bool replyFinished=false;
    auto *reply = modbusDevice->sendReadRequest(readRequest(8, 1), m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
            //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadZeroTraceRange);
        } else {
            replyFinished = true;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        return;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 1)
            {
                m_zeroTraceRange =unit.value(0);
                //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
                //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
                emit zeroTraceRangeChanged(m_zeroTraceRange);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }

    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::getADSampleRate()
{
    if(!modbusDevice)
    {
        return;
    }

    bool replyFinished=false;
    auto *reply = modbusDevice->sendReadRequest(readRequest(13, 1), m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
            //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadADSampleRate);
        } else {
            replyFinished=true;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        return;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 1)
            {
                m_aDSampleRate =unit.value(0);
                //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
                //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
                emit aDSampleRateChanged(m_aDSampleRate);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }

    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

int MyModBus::getMaxRange()
{
//    if(!modbusDevice)
//    {
//        return;
//    }
//    if (auto *reply = modbusDevice->sendReadRequest(readRequest(20, 2), m_slaveID)) {
//        if (!reply->isFinished())
//        {
//            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadMaxRange);
//        } else {
//            delete reply;
//        }

//    }
//    else
//    {
//        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
//    }
    if(!modbusDevice)
    {
        return -1;
    }
    auto *reply = modbusDevice->sendReadRequest(readRequest(20, 2), m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
            //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadMaxRange);
        } else {
            //reply->deleteLater();
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        return -1;
    }
    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            //reply->deleteLater();
            m_maxRange = byteArrayToInt(arry);
            delete reply;
            reply = nullptr;
            return m_maxRange;
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return -1;
}

bool MyModBus::zeroCalibration()
{
    bool result =false;
    if(!modbusDevice)
    {
        return result;
    }
    modbusDevice->setTimeout(6000);
    QModbusDataUnit writeUnit = writeRequest(22,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();
    int weight =1;
    int value0=weight&0x0000ffff;
    int value1=(weight&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            QTimer::singleShot(6000, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }


    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        result = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    modbusDevice->setTimeout(60);
    return result;
}

bool MyModBus::gainCalibration(int index, int value)
{
    bool result =false;
    if(!modbusDevice)
    {
        return result;
    }
    modbusDevice->setTimeout(6000);
    int startAddr=30;
    if(index == 1)
    {
        startAddr=32;
    }
    else if(index == 2)
    {
        startAddr=34;
    }
    else if(index == 3)
    {
        startAddr=36;
    }
    QModbusDataUnit writeUnit = writeRequest(startAddr,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    int value0=value&0x0000ffff;
    int value1=(value&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            QTimer::singleShot(6000, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }

    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        result = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    modbusDevice->setTimeout(60);
    return result;
}

bool MyModBus::gainCalibrationAll(int index, int value)
{
    bool res = false;
    for(int i = 0; i < m_axisCount; i++)
    {
        res = gainCalibration(index, value, i);
        if(!res)
        {
            return res;
        }
        QThread::msleep(10);
    }
    return true;
}

bool MyModBus::gainCalibration(int index, int value, int deviceIndex)
{
    bool result =false;
    if(!modbusDevice)
    {
        return result;
    }
    if(deviceIndex >= m_slaveIDs.length())
    {
        return result;
    }
    modbusDevice->setTimeout(6000);
    int startAddr=30;
    if(index == 1)
    {
        startAddr=32;
    }
    else if(index == 2)
    {
        startAddr=34;
    }
    else if(index == 3)
    {
        startAddr=36;
    }
    QModbusDataUnit writeUnit = writeRequest(startAddr,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    int value0=value&0x0000ffff;
    int value1=(value&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveIDs.at(deviceIndex));
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
        //        else {
        //            // broadcast replies return immediately

        //            reply->deleteLater();
        //        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }

    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        result = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    modbusDevice->setTimeout(60);
    return result;
}

void MyModBus::reset()
{
    if(!modbusDevice)
    {
        return;
    }
    QModbusDataUnit writeUnit = writeRequest(6,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, 1);

    //serverEdit 发生给slave的ID
    if (auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID)) {
        if (!reply->isFinished()) {
            connect(reply, &QModbusReply::finished, this, [this, reply]() {
                if (reply->error() == QModbusDevice::ProtocolError) {
                    QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                         .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
                    qDebug()<<errStr;
                } else if (reply->error() != QModbusDevice::NoError) {
                    qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                                arg(reply->errorString()).arg(reply->error(), -1, 16);
                }
                else if(reply->error() == QModbusDevice::NoError){
                }
                //reply->deleteLater();
                delete reply;
                //reply = nullptr;
            });
        } else {
            // broadcast replies return immediately

            //reply->deleteLater();
            delete reply;
            reply = nullptr;
        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getHoldMode()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(73, 1), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadHoldMode);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getHoldTriggerCondition()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(74, 1), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadHoldTriggerCondition);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getZeroValue()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(75, 2), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadZeroValue);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getHoldResult()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(77, 2), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadHoldResult);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getPreIsStable1()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(40, 1), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreIsStable1);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getPreMinDuration1()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(41, 1), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreMinDuration1);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getPreCondition1()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(42, 1), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreCondition1);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getPreValue11()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(43, 2), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreValue11);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

void MyModBus::getPreValue21()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(45, 2), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreValue21);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

bool MyModBus::setHoldModeCondition(int holdMode, int holdTriggerCondition)
{
    bool res = false;
        if(!modbusDevice)
        {
            return res;
        }
        QModbusDataUnit writeUnit = writeRequest(73,2);
        //QModbusDataUnit::RegisterType table = writeUnit.registerType();

        writeUnit.setValue(0, holdMode);
        writeUnit.setValue(1, holdTriggerCondition);

        //serverEdit 发生给slave的ID
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
        if (reply) {
            if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                eventLoop.exec();
            }
//            else {
//                // broadcast replies return immediately

//                reply->deleteLater();
//            }
        } else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            return res;
        }

        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            m_holdMode = holdMode;
            m_holdTriggerCondition = holdTriggerCondition;
            res = true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return res;
}

bool MyModBus::setPrePosPara(int posIndex, int isStable, int minDuration, int condition)
{
        bool res = false;
        if(!modbusDevice)
        {
            return res;
        }
        int startAddr = 40;
        if(posIndex == 1)
        {
            startAddr = 47;
        }
        else if(posIndex == 2)
        {
            startAddr = 54;
        }
        else if(posIndex == 3)
        {
            startAddr = 61;
        }
        QModbusDataUnit writeUnit = writeRequest(startAddr,3);
        //QModbusDataUnit::RegisterType table = writeUnit.registerType();

        writeUnit.setValue(0, isStable);
        writeUnit.setValue(1, minDuration);
        writeUnit.setValue(2, condition);

        //serverEdit 发生给slave的ID
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
        if (reply) {
            if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                eventLoop.exec();
            }
//            else {
//                // broadcast replies return immediately

//                reply->deleteLater();
//            }
        } else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            return res;
        }
        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            if(posIndex == 1)
            {
                m_preIsStable2 = isStable;
                m_preMinDuration2 = minDuration;
                m_preCondition2 =condition;
            }
            else if(posIndex == 2)
            {
                m_preIsStable3 = isStable;
                m_preMinDuration3 = minDuration;
                m_preCondition3 =condition;
            }
            else if(posIndex == 3)
            {
                m_preIsStable4 = isStable;
                m_preMinDuration4 = minDuration;
                m_preCondition4 =condition;
            }
            else
            {
                m_preIsStable1 = isStable;
                m_preMinDuration1 = minDuration;
                m_preCondition1 =condition;
            }
            res = true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return res;
}

void MyModBus::getPreIsStable2()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(47, 1), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreIsStable2);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreMinDuration2()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(48, 1), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreMinDuration2);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreCondition2()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(49, 1), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreCondition2);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreValue12()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(50, 2), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreValue12);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreValue22()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(52, 2), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreValue22);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreIsStable3()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(54, 1), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreIsStable3);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreMinDuration3()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(55, 1), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreMinDuration3);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreCondition3()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(56, 1), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreCondition3);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreValue13()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(57, 2), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreValue13);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreValue23()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(59, 2), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreValue23);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreIsStable4()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(61, 1), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreIsStable4);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreMinDuration4()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(62, 1), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreMinDuration4);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreCondition4()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(63, 1), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreCondition4);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreValue14()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(64, 2), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreValue14);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getPreValue24()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(66, 2), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPreValue24);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

bool MyModBus::resetAll(int deviceID)
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        if(deviceID >= m_slaveIDs.length())
        {
            return result;
        }
        QModbusDataUnit writeUnit = writeRequest(9, 1, QModbusDataUnit::Coils);

        writeUnit.setValue(0, 0xFF00);

        //serverEdit 发生给slave的ID
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveIDs.at(deviceID));
        if (reply) {
            if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                eventLoop.exec();
            }
//            else {
//                // broadcast replies return immediately

//                reply->deleteLater();
//            }
        } else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            return result;
        }
        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            result =true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return result;
}

bool MyModBus::resetCal(int deviceID)
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        if(deviceID >= m_slaveIDs.length())
        {
            return result;
        }
        QModbusDataUnit writeUnit = writeRequest(10, 1, QModbusDataUnit::Coils);

        writeUnit.setValue(0, 0xFF00);

        //serverEdit 发生给slave的ID
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveIDs.at(deviceID));
        if (reply) {
            if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                eventLoop.exec();
            }
//            else {
//                // broadcast replies return immediately

//                reply->deleteLater();
//            }
        }
        else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            return result;
        }

        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            result = true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return result;
}
bool MyModBus::resetPara(int deviceID)
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        if(deviceID >= m_slaveIDs.length())
        {
            return result;
        }
        QModbusDataUnit writeUnit = writeRequest(11, 1, QModbusDataUnit::Coils);

        writeUnit.setValue(0, 0xFF00);

        //serverEdit 发生给slave的ID
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveIDs.at(deviceID));
        if (reply) {
            if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                eventLoop.exec();
            }
//            else {
//                // broadcast replies return immediately

//                reply->deleteLater();
//            }
        } else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            return result;
        }

        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            result = true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return result;
}

bool MyModBus::resetAll()
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        modbusDevice->setTimeout(6000);
        QModbusDataUnit writeUnit = writeRequest(9, 1, QModbusDataUnit::Coils);

        writeUnit.setValue(0, 0xFF00);

        //serverEdit 发生给slave的ID
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
        if (reply) {
            if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                QTimer::singleShot(6000, &eventLoop, &QEventLoop::quit);
                eventLoop.exec();
            }
            //            else {
            //                // broadcast replies return immediately

            //                reply->deleteLater();
            //            }
        } else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            modbusDevice->setTimeout(60);
            return result;
        }
        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            result =true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        modbusDevice->setTimeout(60);
        return result;
}

bool MyModBus::resetCal()
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        modbusDevice->setTimeout(6000);
        QModbusDataUnit writeUnit = writeRequest(10, 1, QModbusDataUnit::Coils);

        writeUnit.setValue(0, 0xFF00);

        //serverEdit 发生给slave的ID
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
        if (reply) {
            if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                QTimer::singleShot(6000, &eventLoop, &QEventLoop::quit);
                eventLoop.exec();
            }
            //            else {
            //                // broadcast replies return immediately

            //                reply->deleteLater();
            //            }
        }
        else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            modbusDevice->setTimeout(60);
            return result;
        }

        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            result = true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        modbusDevice->setTimeout(60);
        return result;
}

bool MyModBus::resetPara()
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        modbusDevice->setTimeout(6000);
        QModbusDataUnit writeUnit = writeRequest(11, 1, QModbusDataUnit::Coils);

        writeUnit.setValue(0, 0xFF00);

        //serverEdit 发生给slave的ID
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
        if (reply) {
            if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                QTimer::singleShot(6000, &eventLoop, &QEventLoop::quit);
                eventLoop.exec();
            }
            //            else {
            //                // broadcast replies return immediately

            //                reply->deleteLater();
            //            }
        } else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            modbusDevice->setTimeout(60);
            return result;
        }

        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            result = true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        modbusDevice->setTimeout(6000);
        return result;
}

//bool MyModBus::resetZeroValue()
//{
//    return  setZeroValue_(0);
//}

bool MyModBus::resetSwitch()
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        QModbusDataUnit writeUnit = writeRequest(12, 1, QModbusDataUnit::Coils);

        writeUnit.setValue(0, 0xFF00);
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
        //serverEdit 发生给slave的ID
        if (reply) {
            if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                eventLoop.exec();
            }
//            else {
//                // broadcast replies return immediately

//                reply->deleteLater();
//            }
        } else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            return result;
        }

        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            result = true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return result;
}

void MyModBus::getStable()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(0, 1, QModbusDataUnit::Coils), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadStable);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}
void MyModBus::getNormal()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(1, 1, QModbusDataUnit::Coils), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadNormal);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}
void MyModBus::getZero()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(2, 1, QModbusDataUnit::Coils), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadZero);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}
void MyModBus::getPositive()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(3, 1, QModbusDataUnit::Coils), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadPositive);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getCurrent0()
{
        if(!modbusDevice)
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(22, 2), m_slaveID)) {
            if (!reply->isFinished())
            {
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadCurrent0);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getCollectTime()
{
        /*QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("mydatabase.db");
        if(!db.open())
        {
            return;
        }
        QSqlQuery* query = new QSqlQuery(db);*/
        if(!m_db.isOpen())
        {
            m_db.open();
        }


        QString queryser= QString("select "
                                   "collectTime "
                                   "from "
                                   "configTable where id = 1;");
        m_query->exec(queryser);
        if(m_query->next())
        {
            m_collectTime = m_query->value(0).toInt();
            emit collectTimeChanged(m_collectTime);
        }
        else
        {
            qDebug()<<m_query->lastError();
        }

        m_query->finish();
        //db.close();
}

void MyModBus::getNormalParas()
{
        if(!modbusDevice)
        {
            return;
        }
        auto *reply = modbusDevice->sendReadRequest(readRequest(11, 9), m_slaveID);
        if (reply) {
            if (!reply->isFinished())
            {
//                QEventLoop eventLoop;
//                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
//                eventLoop.exec();
                connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadNormalPara);
            } else {
                delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

void MyModBus::getVoltage()
{
        if(!modbusDevice)
        {
            return;
        }
//        if(m_decimalPlaces < 0)
//        {
//            getDecimalPlaces();
//        }
        for(int i=0 ; i<m_slaveIDs.length();i++)
        {
            if (auto *reply = modbusDevice->sendReadRequest(readRequest(22, 2), m_slaveIDs.at(i))) {
                if (!reply->isFinished())
                {
                    connect(reply, &QModbusReply::finished, this, [=](){
                        slotReadVoltage(i);
                    });
                } else {
                    delete reply;
                }
                QThread::msleep(20);
            }
            else
            {
                qDebug()<<tr("Read error: ") + modbusDevice->errorString();
            }
        }
}
void MyModBus::connectSerialPort()
{
    if(!modbusDevice)
    {
        return;
    }
    modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter,
                                         m_comName);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter,
                                         m_parity > 0 ? m_parity + 1 : 0);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,
                                         m_baudrate);
    modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter,
                                         m_dataBit);
    QSerialPort::StopBits stopBit;
    switch(m_stopBit)
    {
        case 0:
            stopBit = QSerialPort::OneStop;
            break;
        case 1:
            stopBit = QSerialPort::OneAndHalfStop;
            break;
        case 2:
            stopBit = QSerialPort::TwoStop;
            break;
        default:
            stopBit = QSerialPort::OneStop;
            break;
    }
    modbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter,
                                         stopBit);
    modbusDevice->setTimeout(60);
    modbusDevice->setNumberOfRetries(3);
    if (!modbusDevice->connectDevice()) {
        setSensorConnStatus(0);
        //m_encoderConnStatus = false;
    }
    else
    {
        //getDecimalPlaces();
        setSensorConnStatus(1);
        //m_encoderConnStatus = true;
        //saveEncoderParaSP(m_encoderDirection, m_encoderFiltering);
    }
}

void MyModBus::connectEncoder()
{
    if(!encoderModbusDevice)
    {
        return;
    }
    encoderModbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter,
                                         m_comNameEncoder);
    encoderModbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter,
                                         m_parityEncoder > 0 ? m_parityEncoder + 1 : 0);
    encoderModbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,
                                         m_baudrateEncoder);
    encoderModbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter,
                                         m_dataBitEncoder);
    QSerialPort::StopBits stopBit;
    switch(m_stopBitEncoder)
    {
        case 0:
            stopBit = QSerialPort::OneStop;
            break;
        case 1:
            stopBit = QSerialPort::OneAndHalfStop;
            break;
        case 2:
            stopBit = QSerialPort::TwoStop;
            break;
        default:
            stopBit = QSerialPort::OneStop;
    }
    encoderModbusDevice->setConnectionParameter(QModbusDevice::SerialStopBitsParameter,
                                         stopBit);
    encoderModbusDevice->setTimeout(60);
    encoderModbusDevice->setNumberOfRetries(3);
    if (!encoderModbusDevice->connectDevice()) {
        m_encoderConnStatus = false;
    }
    else
    {
        m_encoderConnStatus = true;
        saveEncoderParaSP(m_encoderDirection, m_encoderFiltering);
    }
}

void MyModBus::connect4g()
{
    if(m_comName4g.isEmpty())
    {
        return;
    }
    if(serialPort4g!=nullptr)
    {
        disconnect(serialPort4g,SIGNAL(readyRead()),0,0);
        serialPort4g->clear();
        serialPort4g->close();        
        delete serialPort4g;
        serialPort4g = nullptr;
    }
    serialPort4g = new QSerialPort;
    serialPort4g->setPortName(m_comName4g);
    QSerialPort::BaudRate baudRate;
    //[9600,19200,38400,57600,115200]
    switch(m_baudrate4g)
    {
        case 9600:
            baudRate = QSerialPort::Baud9600;
            break;
        case 19200:
            baudRate = QSerialPort::Baud19200;
            break;
        case 38400:
            baudRate = QSerialPort::Baud38400;
            break;
        case 57600:
            baudRate = QSerialPort::Baud57600;
            break;
        case 115200:
            baudRate = QSerialPort::Baud115200;
            break;
        default:
            baudRate = QSerialPort::Baud9600;
            break;
    }
    serialPort4g->setBaudRate(baudRate);
    //[5,6,7,8]
    QSerialPort::DataBits dataBits;
    switch(m_dataBit4g)
    {
        case 5:
                dataBits=QSerialPort::Data5;
                break;
        case 6:
                dataBits=QSerialPort::Data6;
                break;
        case 7:
                dataBits=QSerialPort::Data7;
                break;
        case 8:
                dataBits=QSerialPort::Data8;
                break;
        default:
                dataBits=QSerialPort::Data8;
                break;

    }
    serialPort4g->setDataBits(dataBits);
    //[1,3,2]
    QSerialPort::StopBits stopBits;
    switch(m_stopBit)
    {
        case 0:
                stopBits=QSerialPort::OneStop;
                break;
        case 2:
                stopBits=QSerialPort::TwoStop;
                break;
        case 1:
                stopBits=QSerialPort::OneAndHalfStop;
                break;
        default:
                stopBits=QSerialPort::OneStop;
                break;
    }
    serialPort4g->setStopBits(stopBits);
    //1-偶校验,2-奇校验,0-无校验
    QSerialPort::Parity parity;
    switch(m_parity4g)
    {
        case 0:
                parity=QSerialPort::NoParity;
                break;
        case 1:
                parity=QSerialPort::EvenParity;
                break;
        case 2:
                parity=QSerialPort::OddParity;
                break;
        default:
                parity=QSerialPort::NoParity;
                break;

    }
    serialPort4g->setParity(parity);
    serialPort4g->setFlowControl(QSerialPort::NoFlowControl);
    serialPort4g->setReadBufferSize(8192); 
    //serialPort4g->
    if (serialPort4g->open(QIODevice::ReadWrite))
    {
        m_4gConnStatus = 1;
        disconnect(serialPort4g,SIGNAL(readyRead()),0,0);
        connect(serialPort4g,SIGNAL(readyRead()),this,SLOT(read4gData()));      //C QIODevice::readyRead().
    }
    else
    {
        #if DEBUG_4G
        qDebug()<<"4g connect error!";
        #endif
        m_4gConnStatus = 0;
    }
}
QString MyModBus::softwareVersion()
{
    return m_softwareVersion;
}
void MyModBus::getSoftwareVersion()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(9000, 2), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadVersion);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}
void MyModBus::slotReadVersion()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar value0 =unit.value(1)&0x00FF;
            uchar value1 =(unit.value(1)&0xFF00)>>8;
            uchar value2 =unit.value(0)&0x00FF;
            uchar value3 =(unit.value(0)&0xFF00)>>8;
            m_softwareVersion =QString::number(value3, 16)+" "+QString::number(value2, 16)+" "+QString::number(value1, 16)+" "+QString::number(value0, 16);
                //QString::number(value2, 16)+"-"+QString::number(value1, 16)+"-"+QString::number(value0, 16);
            emit softwareVersionChanged(m_softwareVersion);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

/*创建QModbusDataUnit.
 * startAddress: 启始地址
 * numberOfEntries: 寄存器个数
 * type: 功能码类型，默认HoldingRegisters。
*/
QModbusDataUnit MyModBus::readRequest(int startAddress, int numberOfEntries, int type) const
{
    const auto table =
        static_cast<QModbusDataUnit::RegisterType> (type);
    return QModbusDataUnit (table, startAddress, numberOfEntries);
}

QModbusDataUnit MyModBus::writeRequest(int startAddress, int numberOfEntries, int type) const
{
    const auto table =
        static_cast<QModbusDataUnit::RegisterType> (type);
    return QModbusDataUnit (table, startAddress, numberOfEntries);
}
QString MyModBus::devDate()
{
    return m_devDate;
}
void MyModBus::getDevDate()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(9002, 2), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadDevDate);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}
void MyModBus::slotReadDevDate()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar value0 =unit.value(1)&0x00FF;
            uchar value1 =(unit.value(1)&0xFF00)>>8;
            uchar value2 =unit.value(0)&0x00FF;
            uchar value3 =(unit.value(0)&0xFF00)>>8;
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            m_devDate=QString::number(value3, 16)+" "+QString::number(value2, 16)+" "+QString::number(value1, 16)+" "+QString::number(value0, 16);
                //"20"+QString::number(value2, 16)+"-"+QString::number(value1, 16)+"-"+QString::number(value0, 16);
            emit devDateChanged(m_devDate);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}
QString MyModBus::weight()
{
    return m_weightData;
}

int MyModBus::decimalPlaces()
{
    return m_decimalPlaces;
}

bool MyModBus::setDecimalPlaces(int decimalPlaces)
{
    bool result =false;
    if(!modbusDevice)
    {
        return result;
    }

    QModbusDataUnit writeUnit = writeRequest(18,1);
    writeUnit.setValue(0, decimalPlaces);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        //        else {
        //            // broadcast replies return immediately

        //            reply->deleteLater();
        //        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }

    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return result;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return result;
    }
    else if(reply->error() == QModbusDevice::NoError){
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        m_decimalPlaces=decimalPlaces;
    }
    result = true;
    return result;
}

int MyModBus::minGraduation()
{
    return m_minGraduation;
}

bool MyModBus::setMinGraduation(int minGraduation)
{
    bool result =false;
    if(!modbusDevice)
    {
        return result;
    }
    QModbusDataUnit writeUnit = writeRequest(19,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, minGraduation);
    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        //        else {
        //            // broadcast replies return immediately

        //            reply->deleteLater();
        //        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }

    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;

        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return result;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);

        reply->deleteLater();
        delete reply;
        reply = nullptr;
        return result;
    }
    else if(reply->error() == QModbusDevice::NoError){
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
    }
    m_minGraduation = minGraduation;
    result =true;
    return result;
}

QString MyModBus::unit()
{
    return m_unit;
}

bool MyModBus::setUnit(QString unit)
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET unit = '%1' WHERE id = 1;")
                           .arg(unit);
    bool updated = m_query->exec(queryser);
    if(!updated){
        //db.close();
        m_query->lastError();
        m_query->finish();
        return result;
    }
    m_query->finish();
    //db.close();
    m_unit=unit;
    emit unitChanged(m_unit);
    result = true;
    return result;
}

double MyModBus::upperUpperLimit()
{
    return m_upperUpperLimit;
}

bool MyModBus::setUpperUpperLimit(double upperUpperLimit)
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    bool result =false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET upperUpperLimit = %1 WHERE id = 1;")
                           .arg(upperUpperLimit);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_upperUpperLimit=upperUpperLimit;
    emit upperUpperLimitChanged(m_upperUpperLimit);
    result = true;
    return result;
}

double MyModBus::upperLimit()
{
    return m_upperLimit;
}

bool MyModBus::setUpperLimit(double upperLimit)
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    bool result =false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET upperLimit = %1 WHERE id = 1;")
                           .arg(upperLimit);
    bool updated = m_query->exec(queryser);
    if(!updated){
        //db.close();
        m_query->finish();
        return result;
    }
    m_query->finish();
    //db.close();
    m_upperLimit=upperLimit;
    emit upperLimitChanged(m_upperLimit);
    result = true;
    return result;
}

double MyModBus::lowerLimit()
{

    return m_lowerLimit;
}

bool MyModBus::setLowerLimit(double lowerLimit)
{/*
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("mydatabase.db");
    if(!db.open())
    {
        return;
    }
    QSqlQuery* query = new QSqlQuery(db);*/
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET lowerLimit = %1 WHERE id = 1;")
                           .arg(lowerLimit);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_lowerLimit=lowerLimit;
    emit lowerLimitChanged(m_lowerLimit);
    result = true;
    return result;
}

double MyModBus::lowerLowerLimit()
{
    return m_lowerLowerLimit;
}

bool MyModBus::setLowerLowerLimit(double lowerLowerLimit)
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }

    QString queryser= QString("UPDATE configTable SET lowerLowerLimit = %1 WHERE id = 1;")
                           .arg(lowerLowerLimit);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_lowerLowerLimit=lowerLowerLimit;
    emit lowerLowerLimitChanged(m_lowerLowerLimit);
    result = true;
    return result;
}

int MyModBus::steadyStateFiltering()
{
    return m_steadyStateFiltering;
}

bool MyModBus::setSteadyStateFiltering(int steadyStateFiltering)
{
    bool result =false;
    if(!modbusDevice)
    {
        return result;
    }
    QModbusDataUnit writeUnit = writeRequest(12,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, steadyStateFiltering);
    bool replyFinished = false;
    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        else {
            replyFinished = true;
        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            m_steadyStateFiltering = steadyStateFiltering;
            result = true;
        }
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return result;
}

int MyModBus::digitalFiltering()
{
    return m_digitalFiltering;
}

bool MyModBus::setDigitalFiltering(int digitalFiltering)
{
    bool result = false;
    if(!modbusDevice)
    {
        return result;
    }
    QModbusDataUnit writeUnit = writeRequest(11,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, digitalFiltering);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_digitalFiltering = digitalFiltering;
        result = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return result;
}

int MyModBus::slaveID()
{
    return m_slaveID;
}

bool MyModBus::setSlaveID(int slaveID)
{
//    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("mydatabase.db");
//    if(!db.open())
//    {
//        return;
//    }
//    QSqlQuery* query = new QSqlQuery(db);
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET dt45SlaveId = %1 WHERE id = 1;")
                           .arg(slaveID);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_slaveID=slaveID;
    emit lowerLimitChanged(m_slaveID);
    result = true;
    return result;
}

int MyModBus::stabilityRange()
{
    return m_stabilityRange;
}

bool MyModBus::setStabilityRange(int stabilityRange)
{
    bool result = false;
    if(!modbusDevice)
    {
        return result;
    }
    QModbusDataUnit writeUnit = writeRequest(9,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, stabilityRange);
    bool replyFinished = false;
    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        else {
            replyFinished = true;
        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            m_stabilityRange = stabilityRange;
            result = true;
        }
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return result;
}

int MyModBus::clearRange()
{
    return m_clearRange;
}

bool MyModBus::setClearRange(int clearRange)
{
    bool res= false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(10,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, clearRange);

    bool replyFinished = false;
    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        else {
            replyFinished = true;
        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            m_clearRange = clearRange;
            res =true;
        }
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::powerAutoZero()
{
    return m_powerAutoZero;
}

bool MyModBus::setPowerAutoZero(int powerAutoZero)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(7,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, powerAutoZero);
    bool replyFinished = false;
    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        else {
            replyFinished=true;
        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            m_powerAutoZero = powerAutoZero;
            res = true;
        }
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::zeroTraceRange()
{
    return m_zeroTraceRange;
}

bool MyModBus::setZeroTraceRange(int zeroTraceRange)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(8,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, zeroTraceRange);

    bool replyFinished = false;
    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        else {
            replyFinished = true;
        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            m_zeroTraceRange = zeroTraceRange;
            res = true;
        }
    }
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::aDSampleRate()
{
    return m_aDSampleRate;
}

bool MyModBus::setADSampleRate(int aDSampleRate)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(13,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, aDSampleRate);
    bool replyFinished = false;
    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        else {
            replyFinished = true;
        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            m_aDSampleRate = aDSampleRate;
            res = true;
        }
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::maxRange()
{
    return m_maxRange;
}

bool MyModBus::setMaxRange(int maxRange)
{
    bool result = false;
    if(!modbusDevice)
    {
        return result;
    }
    QModbusDataUnit writeUnit = writeRequest(20,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();
    int value0=maxRange&0x0000ffff;
    int value1=(maxRange&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);


    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        //        else {
        //            // broadcast replies return immediately

        //            reply->deleteLater();
        //        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }

    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return result;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
        delete reply;
        reply = nullptr;
        //reply->deleteLater();
        return result;
    }
    else if(reply->error() == QModbusDevice::NoError){
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
    }
    m_maxRange = maxRange;
    result = true;
    return result;
}

int MyModBus::holdMode()
{
    return m_holdMode;
}

//void MyModBus::setHoldMode(int holdMode)
//{
//    if(!modbusDevice)
//    {
//        return;
//    }
//    QModbusDataUnit writeUnit = writeRequest(73,1);
//    QModbusDataUnit::RegisterType table = writeUnit.registerType();

//    writeUnit.setValue(0, holdMode);

//    //serverEdit 发生给slave的ID
//    if (auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID)) {
//        if (!reply->isFinished()) {
//            connect(reply, &QModbusReply::finished, this, [this, reply, holdMode]() {
//                if (reply->error() == QModbusDevice::ProtocolError) {
//                    QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
//                                         .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
//                    qDebug()<<errStr;
//                } else if (reply->error() != QModbusDevice::NoError) {
//                    qDebug()<<tr("Write response error: %1 (code: 0x%2)").
//                                arg(reply->errorString()).arg(reply->error(), -1, 16);
//                }
//                else if(reply->error() == QModbusDevice::NoError){
//                    m_holdMode = holdMode;
//                }
//                reply->deleteLater();
//            });
//        } else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
//    } else {
//        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
//    }
//}

int MyModBus::holdTriggerCondition()
{
    return m_holdTriggerCondition;
}

//void MyModBus::setHoldTriggerCondition(int holdTriggerCondition)
//{
//    if(!modbusDevice)
//    {
//        return;
//    }
//    QModbusDataUnit writeUnit = writeRequest(74,1);
//    QModbusDataUnit::RegisterType table = writeUnit.registerType();

//    writeUnit.setValue(0, holdTriggerCondition);

//    //serverEdit 发生给slave的ID
//    if (auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID)) {
//        if (!reply->isFinished()) {
//            connect(reply, &QModbusReply::finished, this, [this, reply, holdTriggerCondition]() {
//                if (reply->error() == QModbusDevice::ProtocolError) {
//                    QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
//                                         .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
//                    qDebug()<<errStr;
//                } else if (reply->error() != QModbusDevice::NoError) {
//                    qDebug()<<tr("Write response error: %1 (code: 0x%2)").
//                                arg(reply->errorString()).arg(reply->error(), -1, 16);
//                }
//                else if(reply->error() == QModbusDevice::NoError){
//                    m_holdTriggerCondition = holdTriggerCondition;
//                }
//                reply->deleteLater();
//            });
//        } else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
//    } else {
//        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
//    }
//}

int MyModBus::zeroValue()
{
    return m_zeroValue;
}

bool MyModBus::setZeroValue(int zeroValue)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(75,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();
    int value0=zeroValue&0x0000ffff;
    int value1=(zeroValue&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_zeroValue = zeroValue;
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::holdResult()
{
    return m_holdResult;
}

int MyModBus::preIsStable1()
{
    return m_preIsStable1;
}

//void MyModBus::setPreIsStable1(int preIsStable1)
//{
//    if(!modbusDevice)
//    {
//        return;
//    }
//    QModbusDataUnit writeUnit = writeRequest(40,1);
//    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

//    writeUnit.setValue(0, preIsStable1);

//    //serverEdit 发生给slave的ID
//    if (auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID)) {
//        if (!reply->isFinished()) {
//            connect(reply, &QModbusReply::finished, this, [this, reply, preIsStable1]() {
//                if (reply->error() == QModbusDevice::ProtocolError) {
//                    QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
//                                         .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
//                    qDebug()<<errStr;
//                } else if (reply->error() != QModbusDevice::NoError) {
//                    qDebug()<<tr("Write response error: %1 (code: 0x%2)").
//                                arg(reply->errorString()).arg(reply->error(), -1, 16);
//                }
//                else if(reply->error() == QModbusDevice::NoError){
//                    m_preIsStable1 = preIsStable1;
//                }
//                reply->deleteLater();
//            });
//        } else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
//    } else {
//        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
//    }
//}

int MyModBus::preMinDuration1()
{
    return m_preMinDuration1;
}

//void MyModBus::setPreMinDuration1(int preMinDuration1)
//{
//    if(!modbusDevice)
//    {
//        return;
//    }
//    QModbusDataUnit writeUnit = writeRequest(41,1);
//    QModbusDataUnit::RegisterType table = writeUnit.registerType();

//    writeUnit.setValue(0, preMinDuration1);

//    //serverEdit 发生给slave的ID
//    if (auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID)) {
//        if (!reply->isFinished()) {
//            connect(reply, &QModbusReply::finished, this, [this, reply, preMinDuration1]() {
//                if (reply->error() == QModbusDevice::ProtocolError) {
//                    QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
//                                         .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
//                    qDebug()<<errStr;
//                } else if (reply->error() != QModbusDevice::NoError) {
//                    qDebug()<<tr("Write response error: %1 (code: 0x%2)").
//                                arg(reply->errorString()).arg(reply->error(), -1, 16);
//                }
//                else if(reply->error() == QModbusDevice::NoError){
//                    m_preMinDuration1 = preMinDuration1;
//                }
//                reply->deleteLater();
//            });
//        } else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
//    } else {
//        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
//    }
//}

int MyModBus::preCondition1()
{
    return m_preCondition1;
}

//void MyModBus::setPreCondition1(int preCondition1)
//{
//    if(!modbusDevice)
//    {
//        return;
//    }
//    QModbusDataUnit writeUnit = writeRequest(42,1);
//    QModbusDataUnit::RegisterType table = writeUnit.registerType();

//    writeUnit.setValue(0, preCondition1);

//    //serverEdit 发生给slave的ID
//    if (auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID)) {
//        if (!reply->isFinished()) {
//            connect(reply, &QModbusReply::finished, this, [this, reply, preCondition1]() {
//                if (reply->error() == QModbusDevice::ProtocolError) {
//                    QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
//                                         .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
//                    qDebug()<<errStr;
//                } else if (reply->error() != QModbusDevice::NoError) {
//                    qDebug()<<tr("Write response error: %1 (code: 0x%2)").
//                                arg(reply->errorString()).arg(reply->error(), -1, 16);
//                }
//                else if(reply->error() == QModbusDevice::NoError){
//                    m_preCondition1 = preCondition1;
//                }
//                reply->deleteLater();
//            });
//        } else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
//    } else {
//        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
//    }
//}

int MyModBus::preValue11()
{
    return m_preValue11;
}

bool MyModBus::setPreValue11(int preValue11)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(43,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();
    int value0=preValue11&0x0000ffff;
    int value1=(preValue11&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_preValue11 = preValue11;
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::preValue21()
{
    return m_preValue21;
}

bool MyModBus::setPreValue21(int preValue21)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(45,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();
    int value0=preValue21&0x0000ffff;
    int value1=(preValue21&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_preValue21 = preValue21;
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::preIsStable2()
{
    return m_preIsStable2;
}

int MyModBus::preMinDuration2()
{
    return m_preMinDuration2;
}

int MyModBus::preCondition2()
{
    return m_preCondition2;
}

int MyModBus::preValue12()
{
    return m_preValue12;
}

bool MyModBus::setPreValue12(int preValue12)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(50,2);
    int value0=preValue12&0x0000ffff;
    int value1=(preValue12&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_preValue12 = preValue12;
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::preValue22()
{
    return m_preValue22;
}

bool MyModBus::setPreValue22(int preValue22)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(52,2);
    int value0=preValue22&0x0000ffff;
    int value1=(preValue22&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_preValue22 = preValue22;
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::preIsStable3()
{
    return m_preIsStable3;
}

int MyModBus::preMinDuration3()
{
    return m_preMinDuration3;
}

int MyModBus::preCondition3()
{
    return m_preCondition3;
}

int MyModBus::preValue13()
{
    return m_preValue13;
}

bool MyModBus::setPreValue13(int preValue13)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(57,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();
    int value0=preValue13&0x0000ffff;
    int value1=(preValue13&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_preValue13 = preValue13;
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::preValue23()
{
    return m_preValue23;
}

bool MyModBus::setPreValue23(int preValue23)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(59,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();
    int value0=preValue23&0x0000ffff;
    int value1=(preValue23&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_preValue23 = preValue23;
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::preIsStable4()
{
    return m_preIsStable4;
}

int MyModBus::preMinDuration4()
{
    return m_preMinDuration4;
}

int MyModBus::preCondition4()
{
    return m_preCondition4;
}

int MyModBus::preValue14()
{
    return m_preValue14;
}

bool MyModBus::setPreValue14(int preValue14)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(64,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();
    int value0=preValue14&0x0000ffff;
    int value1=(preValue14&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_preValue14 = preValue14;
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::preValue24()
{
    return m_preValue24;
}

bool MyModBus::setPreValue24(int preValue24)
{
    bool res = false;
    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(66,2);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();
    int value0=preValue24&0x0000ffff;
    int value1=(preValue24&0xffff0000)>>16;


    writeUnit.setValue(0, value1);
    writeUnit.setValue(1, value0);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
//        else {
//            // broadcast replies return immediately

//            reply->deleteLater();
//        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }
    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        m_preValue24 = preValue24;
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}

int MyModBus::stable()
{
    return m_stable;
}
int MyModBus::normal()
{
    return m_normal;
}
int MyModBus::zero()
{
    return m_zero;
}
int MyModBus::positive()
{
    return m_positive;
}
int MyModBus::batteryLevel()
{
    return m_batteryLevel;
}
int MyModBus::current0()
{
    return m_current0;
}

int MyModBus::collectTime()
{
    return m_collectTime;
}

bool MyModBus::setCollectTime(int collectTime)
{
    /*
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("mydatabase.db");
    if(!db.open())
    {
        return;
    }
    QSqlQuery* query = new QSqlQuery(db);*/
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }

    QString queryser= QString("UPDATE configTable SET collectTime = %1 WHERE id = 1;")
                           .arg(collectTime);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_collectTime=collectTime;
    emit collectTimeChanged(m_collectTime);
    result = true;
    return result;
}

int MyModBus::axisCount()
{
    return m_axisCount;
}

bool MyModBus::setAxisCount(int axisCount)
{
    //    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    //    db.setDatabaseName("mydatabase.db");
    //    if(!db.open())
    //    {
    //        return;
    //    }
    //    QSqlQuery* query = new QSqlQuery(db);
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET axisCount = '%1' WHERE id = 1;")
                           .arg(axisCount);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_axisCount=axisCount;
    emit axisCountChanged(m_axisCount);
    result = true;
    return result;
}

QString MyModBus::addrs()
{
    return m_addrs;
}

bool MyModBus::setAddrs(QString addrs)
{
    //    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    //    db.setDatabaseName("mydatabase.db");
    //    if(!db.open())
    //    {
    //        return;
    //    }
    //    QSqlQuery* query = new QSqlQuery(db);
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET addrs = '%1' WHERE id = 1;")
                           .arg(addrs);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_addrs=addrs;
    if(m_addrs.length()>0){
        QStringList list = m_addrs.split("|", Qt::SkipEmptyParts);
        m_slaveIDs.clear();
        for(int i = 0; i < list.length(); i++)
        {
            m_slaveIDs.append(list.at(i).toInt());
        }
        m_slaveID=list.at(0).toInt();
    }
    emit addrsChanged(m_addrs);
    result = true;
    return result;
}

QString MyModBus::deviceID()
{
    return m_deviceID;
}

QString MyModBus::deviceType()
{
    return m_deviceType;
}

QVariantList MyModBus::factors()
{
    return m_factors;
}

bool MyModBus::setFactors()
{
    bool result = false;
    QString factors = QString("");
    for(int i = 0; i < m_factors.length(); i++)
    {
        factors.append(m_factors[i].toString()+"|");
    }
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET scales = '%1' WHERE id = 1;")
                           .arg(factors);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    result = true;
    return result;
}

QString MyModBus::hostName()
{
    return m_hostName;
}

bool MyModBus::setHostName(QString hostName)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE mqttTable SET hostName = '%1' WHERE id = 1;")
                           .arg(hostName);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_hostName=hostName;
    emit hostNameChanged(m_hostName);
    result = true;
    return result;
}

int MyModBus::port()
{
    return m_port;
}

bool MyModBus::setPort(int port)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE mqttTable SET port = %1 WHERE id = 1;")
                           .arg(port);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_port=port;
    emit portChanged(m_port);
    result = true;
    return result;
}

int MyModBus::backlight()
{
    //qDebug()<<"Backlight:"<<m_Backlight;
    return m_backlight;
}

bool MyModBus::setbacklight(int backlight)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET Backlight = '%1' WHERE id = 1;")
                           .arg(backlight);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_backlight=backlight;
    emit backlightChanged(m_backlight);
    result = true;
    return result;
}

int MyModBus::screenSaveTime()
{
    return m_screenSaveTime;
}

bool MyModBus::setScreenSaveTime(int screenSaveTime)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET screenSaverTime = '%1' WHERE id = 1;")
                           .arg(screenSaveTime);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_screenSaveTime=screenSaveTime;
    result = true;
    return result;
}

QString MyModBus::topic()
{
    return m_topic;
}

bool MyModBus::setTopic(QString topic)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE mqttTable SET topic = '%1' WHERE id = 1;")
                           .arg(topic);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_topic=topic;
    emit topicChanged(m_topic);
    result = true;
    return result;
}

QString MyModBus::subTopic()
{
    return m_subTopic;
}

bool MyModBus::setSubTopic(QString subTopic)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE mqttTable SET subTopic = '%1' WHERE id = 1;")
                           .arg(subTopic);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_subTopic=subTopic;
    emit subTopicChanged(m_subTopic);
    result = true;
    return result;
}

QString MyModBus::userName()
{
    return m_userName;
}

bool MyModBus::setUserName(QString userName)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE mqttTable SET userName = '%1' WHERE id = 1;")
                           .arg(userName);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_userName=userName;
    emit userNameChanged(m_topic);
    result = true;
    return result;
}

QString MyModBus::password()
{
    return m_password;
}

bool MyModBus::setPassword(QString password)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE mqttTable SET pwd = '%1' WHERE id = 1;")
                           .arg(password);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_password=password;
    emit passwordChanged(m_password);
    result = true;
    return result;
}

QString MyModBus::truckNo()
{
    return m_truckNo;
}

bool MyModBus::setTruckNo(QString truckNo)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET truckNo = '%1' WHERE id = 1;")
                           .arg(truckNo);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_truckNo=truckNo;
    emit truckNoChanged(m_truckNo);
    result = true;
    return result;
}

QString MyModBus::clientID()
{
    return m_clientID;
}

bool MyModBus::setClientID(QString clientID)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET clientID = '%1' WHERE id = 1;")
                           .arg(clientID);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_clientID=clientID;
    emit clientIDChanged(m_clientID);
    result = true;
    return result;
}

int MyModBus::mqttSwitch()
{
    return m_mqttSwitch;
}

bool MyModBus::setMqttSwitch(int mqttSwitch)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE mqttTable SET isOpen = %1 WHERE id = 1;")
                           .arg(mqttSwitch);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_mqttSwitch=mqttSwitch;
    emit mqttSwitchChanged(m_mqttSwitch);
    result = true;
    return result;
}

int MyModBus::mqttInterval()
{
    return m_mqttInterval;
}

bool MyModBus::setMqttInterval(int mqttInterval)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE mqttTable SET interval = %1 WHERE id = 1;")
                           .arg(mqttInterval);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    m_mqttInterval=mqttInterval;
    emit mqttIntervalChanged(m_mqttInterval);
    result = true;
    return result;
}

int MyModBus::saveInterval()
{
    return m_saveInterval;
}

bool MyModBus::setSaveInterval(int saveInterval)
{
    m_saveInterval =saveInterval;
    emit saveIntervalChanged(m_saveInterval);
    return true;
}

void MyModBus::getData()
{
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("select "
                               "unit, upperLimit, upperUpperLimit, lowerLimit, lowerLowerLimit, collectTime, axisCount, addrs, scales, deviceID, truckNo, zeroWeight, zeroWeight1, calThreshold"
                               ", encoderChannel, encoderFiltering, encoderDirection, encoderInterval, encoderSlaveId, dt45SlaveId, saveInterval, pulsePerRev, encoderDecimalPlace, deviceType"
                               ", accumulateZero, autoSave, saveDays, Backlight, screenSaverTime "
                               "from "
                               "configTable where id = 1;");
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_unit = m_query->value(0).toString();
        //m_slaveID = query->value(1).toInt();
        m_upperLimit = m_query->value(1).toInt();
        m_upperUpperLimit=m_query->value(2).toInt();
        m_lowerLimit = m_query->value(3).toInt();
        m_lowerLowerLimit=m_query->value(4).toInt();
        m_collectTime =m_query->value(5).toInt();
        m_axisCount =m_query->value(6).toInt();
        m_deviceID = m_query->value(9).toString();
        m_truckNo = m_query->value(10).toString();
        //m_zeroValue_0=m_query->value(11).toFloat();
        m_slaveID = 1;

        QString temp = m_query->value(7).toString();
        m_addrs = temp;
        if(temp.length()>0){
            QStringList list = temp.split("|", Qt::SkipEmptyParts);
            m_slaveIDs.clear();
            for(int i = 0; i < list.length(); i++)
            {
                m_slaveIDs.append(list.at(i).toInt());
            }
            m_slaveID=list.at(0).toInt();
        }
        QString factor = m_query->value(8).toString();
        m_factors.clear();
        if(factor.length()>0){
            QStringList list = factor.split("|", Qt::SkipEmptyParts);
            for(int i=0; i<list.length(); i++)
            {
                m_factors.append(list.at(i).toFloat());
            }
        }

        QString zeroWeight = m_query->value(11).toString();
        m_zeroWeights.clear();
        if(zeroWeight.length()>0){
            QStringList list = zeroWeight.split("|", Qt::SkipEmptyParts);
            for(int i=0; i<list.length(); i++)
            {
                m_zeroWeights.append(list.at(i).toDouble());
            }
        }
        m_zeroWeight1 = m_query->value(12).toDouble();
        m_calThreshold = m_query->value(13).toDouble();
        m_encoderChannel = m_query->value(14).toInt();
        m_encoderFiltering = m_query->value(15).toInt();
        m_encoderDirection = m_query->value(16).toInt();
        m_encoderInterval = m_query->value(17).toInt();
        m_dt45SlaveID = m_query->value(19).toInt();
        m_sensorSlaveID = m_query->value(19).toInt();
        m_encoderSlaveID = m_query->value(18).toInt();
        m_saveInterval = m_query->value(20).toInt();
        m_pulsePerRev=m_query->value(21).toInt();
        m_degreePerPulse=360.0/m_pulsePerRev;
        m_encoderDecimalPlace =m_query->value(22).toInt();
        m_deviceType = m_query->value(23).toString();
        m_accumulateZero = m_query->value(24).toDouble();
        m_autoSave = m_query->value(25).toInt();
        m_saveDays = m_query->value(26).toInt();
        m_backlight = m_query->value(27).toInt();
        m_screenSaveTime = m_query->value(28).toInt();
    }
    else
    {
        qDebug()<<m_query->lastError();
    }

    queryser= QString("select "
                               "hostName, port, topic, userName, pwd, isOpen, interval, clientID, subTopic "
                               "from "
                               "mqttTable where id = 1;");
    m_query->clear();
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_hostName = m_query->value(0).toString();
        m_port = m_query->value(1).toInt();
        m_topic = m_query->value(2).toString();
        m_userName = m_query->value(3).toString();
        m_password = m_query->value(4).toString();
        m_mqttSwitch = m_query->value(5).toInt();
        m_mqttInterval = m_query->value(6).toInt();
        m_clientID = m_query->value(7).toString();
        m_subTopic = m_query->value(8).toString();
    }
    else
    {
        qDebug()<<m_query->lastError();
    }

    queryser= QString("select "
                       "apn, url "
                       "from "
                       "otaTable where id = 1;");
    m_query->clear();
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_apn = m_query->value(0).toString();
        m_url = m_query->value(1).toString();
    }
    else
    {
        qDebug()<<m_query->lastError();
    }

    queryser= QString("select "
                       "version, devTime "
                       "from "
                       "versionTable where id = 1;");
    m_query->clear();
    m_query->exec(queryser);
    if(m_query->next())
    {
        m_version = m_query->value(0).toString();
        m_devTime = m_query->value(1).toString();
    }
    else
    {
        qDebug()<<m_query->lastError();
    }
    m_query->finish();
}

void MyModBus::collectData0()
{
    if(!modbusDevice)
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(0, 4, QModbusDataUnit::Coils), m_slaveID)) {
        if (!reply->isFinished())
        {
            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadCollectData);
        } else {
            delete reply;
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

bool MyModBus::config4g()
{
    if(!serialPort4g)
    {
        return false;
    }
    if(!m_4gConnStatus)
    {
        return false;
    }
    QStringList lst;
    //reconnect4g = true;
    sendCommand("\r\n");
    QThread::msleep(100);
    sendCommand("ATE0\r\n");
    //关闭回显
    //serialPort4g->waitForReadyRead(500);
    QThread::msleep(200);

    set4gCPIN(false);
    set4gCEREG(false);
    set4gOpenMqttClient(false);
    set4gConnMqttClient(false);
    set4gSubSuccess(false);
    QElapsedTimer t;
    t.start();
    int count =0;
    sendCommand("AT+CPIN?\r\n");
    while(!m_cpin && count<30)
    {
        if(t.elapsed()>500)
        {
            sendCommand("AT+CPIN?\r\n");
            count++;
            t.restart();
        }
    }
    if (!m_cpin)
    {
        return false;
    }    

    //读QCCID
    sendCommand("AT+QCCID\r\n");
    QThread::msleep(300);
    
    count =0;
    sendCommand("AT+CEREG?\r\n");
    while(!m_cgreg && count<25)
    {
        if(t.elapsed()>500)
        {
            sendCommand("AT+CEREG?\r\n");
            count++;
            t.restart();
        }
    }
    if (!m_cgreg)
    {
        return false;
    }
    sendCommand("AT+CTZU=3\r\n");
    //serialPort4g->waitForReadyRead(500);
    QThread::msleep(100);
//    if(!m_cgreg)
//    {
//        //return;
//    }
//    sendCommand("AT+QMTCFG=\"timeout\",0,1,0,0\r\n");
//    QThread::msleep(100);
    //AT+QMTCLOSE=<client_idx>

//    QString close=QString("AT+QMTCLOSE=0");
//    sendCommand(close, false, 1000);
//    QThread::msleep(200);

    QString openCmd=QString("AT+QMTOPEN=0,\"%1\",%2\r\n")
                          .arg(m_hostName)
                          .arg(m_port);
    count =0;
    m_error_response=false;
    sendCommand(openCmd);
    int time=1;
    while(!m_openMqttClient && count<5)
    {
        if((t.elapsed()>15000)||m_error_response)
        {
            m_error_response=false;
            sendCommand(openCmd);
            count++;
            t.restart();
            time=1;
        }
        else if(t.elapsed()>time*200)
        {
            time++;
            sendCommand("\r\n");
        }
    }
    if(m_openMqttClient)
    {
        //QString disc=QString("AT+QMTDISC=0");
        //sendCommand(disc, false, 1000);
        //QThread::msleep(200);

        QString connectCmd;
        if(m_userName.length() == 0 && m_password.length() == 0)
        {
            connectCmd=QString("AT+QMTCONN=0,\"%1\"\r\n").arg(m_clientID);
        }
        else
        {
            connectCmd=QString("AT+QMTCONN=0,\"%1\",\"%2\",\"%3\"\r\n")
                            .arg(m_clientID)
                            .arg(m_userName)
                            .arg(m_password);
        }
        
        count =0;
        m_error_response=false;
        sendCommand(connectCmd);
        time=1;
        while(!m_connectMqttClient && count<3)
        {
            if((t.elapsed()>10000)||m_error_response)
            {
                m_error_response=false;
                sendCommand(connectCmd);
                count++;
                t.restart();
                time=1;
            }
            else if(t.elapsed()>time*200)
            {
                sendCommand("\r\n");
                time++;
            }
        }
        if(m_connectMqttClient)
        {
            //QString unsCmd =QString("AT+QMTUNS=0,1,\"%1\",0\r\n").arg(m_subTopic);
            //sendCommand(unsCmd, false, 1000);
            //QThread::msleep(200);

            QString subCmd =QString("AT+QMTSUB=0,1,\"%1\",1\r\n").arg(m_subTopic);
            count =0;
            m_error_response=false;
            sendCommand(subCmd);
            time=1;
            while(!m_subSuccess && count<10)
            {
                if((t.elapsed()>10000)||m_error_response)
                {
                    m_error_response=false;
                    sendCommand(subCmd);
                    count++;
                    t.restart();
                    time=1;
                }
                else if(t.elapsed()>time*200)
                {
                    sendCommand("\r\n");
                    time++;
                }
            }
            if(!m_subSuccess)
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
    //查询系统时间
    m_getclk = false;
    sendCommand("AT+CCLK?\r\n");
    //serialPort4g->waitForReadyRead(500);
    t.restart();
    while (!m_getclk && t.elapsed()<300) {
        //QCoreApplication::processEvents();
        QThread::msleep(50);
        sendCommand("\r\n");
    }
    if(!m_getclk)
    {
        return true;
    }
    //configGPS();
    //serialPort4g->clear();
    //reconnect4g = false;
    return true;
}

QByteArray MyModBus::GPS_Config_Command(uint8_t cfgtype,QByteArray cfgdata)
{
    QByteArray ba;
    unsigned int len = 0;
    switch (cfgtype)
    {
        case 0x00:
            len = 8;
            break;
        case 0x01:
            len = 3;
            break;
        case 0x07:
            len = 15;
            break;
        case 0x09:
            len = 8;
            break;
        case 0x0A:
            len = 4;
            break;
        case 0x0B:
            len = 8;
            break;
        case 0x0C:
            len = 4;
            break;
        case 0x0F:
            len = 2;
            break;
        case 0x40:
            len = 1;
            break;
        case 0x41:
            len = 5;
            break;
        case 0x42:
            len = 20;
            break;
        case 0x10:
            len = 1;
            break;
        default:
            break;
    }
    ba.resize(2+1+1+2+len+2);
    ba[0] = 0xF1;
    ba[1] = 0xD9;
    ba[2] = 0x06;
    ba[3] = cfgtype;
    ba[4] = len & 0xFF;
    ba[5] = len >> 8;
    for(unsigned int i = 0; i < len; i++)
    {
        ba[6+i] = cfgdata[i];
    }
    QByteArray ba1 = Ql_Check_Quectel (ba, ba.size()-2);
    ba[2+1+1+2+len] = ba1[0];
    ba[2+1+1+2+len+1] = ba1[1];
    return ba;
}

//设置GPS消息输出速率 
//msgtype: 0x00 GGA 全球定位系统定位数据
//         0x01 GLL： 地理位置—纬度和经度。
//         0x02 GSA： GNSS 精度因子（DOP）与有效卫星。
//         0x03 GRS： GNSS 距离残差。
//         0x04 GSV： 可视的 GNSS 卫星。
//         0x05 RMC： 推荐的最少专有 GNSS 数据。
//         0x06 VTG： 相对于地面的实际航向和速度。
//         0x07 ZDA： 时间与日期。主要用于输出 UTC 时间，日、月、年；但不支持输出本地时区信息。
//         0x08 GST： GNSS 伪距误差统计。
//speed:   0x00 = 禁用
//         0x01 = 每定位 1 次输出 1 次
//         0x02 = 每定位 2 次输出 1 次
//         ……
//         0x14 = 每定位 20 次输出 1 次

QByteArray MyModBus::GPS_CFG_MSG(uint8_t msgtype,uint8_t speed)
{ 
    QByteArray cmdbuffer;
    cmdbuffer.resize(3);
    cmdbuffer[0] = 0xF0;
    cmdbuffer[1] = msgtype;
    cmdbuffer[2] = speed;
    return GPS_Config_Command(CFG_MSG,cmdbuffer);
}

QByteArray MyModBus::GPS_CFG_PWRCTL(uint32_t msecond)
{ 
    QByteArray cmdbuffer;
    cmdbuffer.resize(20);
    for(int i = 0; i < 20; i++)
    {
        cmdbuffer[i] = 0x00;
    }
    cmdbuffer[1] = 0x01;
    cmdbuffer[4] = msecond & 0x000000FF;
    cmdbuffer[5] = (msecond >> 8) & 0x000000FF;
    cmdbuffer[6] = (msecond >> 16) & 0x000000FF;
    cmdbuffer[7] = (msecond >> 24) & 0x000000FF;
    return GPS_Config_Command(CFG_PWRCTL,cmdbuffer);
}

void MyModBus::configGPS()
{
    if(!serialPort4g)
    {
        return ;
    }
    if(!m_4gConnStatus)
    {
        return ;
    }
#if GPS_4G_IS_ONE
    int count = 0;
    while(count<3)
    {
        sendCommand(QString("AT+QGPS=1\r\n"));
        QThread::msleep(10);
        sendCommand(QString("AT+QGPSCFG=\"nmeasrc\",1\r\n"));
        QThread::msleep(10);
        count++;
    }
#else

    switchToGPS(1);
    //关闭除GGA之外的其他消息输出
    QByteArray cmd0=GPS_CFG_MSG(GPS_MSG_GLL,0);
    sendGPSCommand(cmd0);
    QThread::msleep(10);
    QByteArray cmd1=GPS_CFG_MSG(GPS_MSG_GSA,0);
    sendGPSCommand(cmd1);
    QThread::msleep(10);
    QByteArray cmd2=GPS_CFG_MSG(GPS_MSG_GRS,0);
    sendGPSCommand(cmd2);
    QThread::msleep(10);
    QByteArray cmd3=GPS_CFG_MSG(GPS_MSG_GSV,0);
    sendGPSCommand(cmd3);
    QThread::msleep(10);
    QByteArray cmd4=GPS_CFG_MSG(GPS_MSG_RMC,0);
    sendGPSCommand(cmd4);
    QThread::msleep(10);
    QByteArray cmd5=GPS_CFG_MSG(GPS_MSG_VTG,0);
    sendGPSCommand(cmd5);
    QThread::msleep(10);
    QByteArray cmd6=GPS_CFG_MSG(GPS_MSG_ZDA,0);
    sendGPSCommand(cmd6);
    QThread::msleep(10);
    QByteArray cmd7=GPS_CFG_MSG(GPS_MSG_GST,0);
    sendGPSCommand(cmd7);
    QThread::msleep(10);
    //设定输出间隔为200ms
    QByteArray cmd8=GPS_CFG_PWRCTL(200);
    sendGPSCommand(cmd8);
    QThread::msleep(10);

    switchToGPS(0);

#endif
}
//Buffer is the data array whose checksum needs to be calculated:
QByteArray  MyModBus::Ql_Check_Quectel (QByteArray pData, unsigned int Length)
{
    uint8_t chk1 = 0;
    uint8_t chk2 = 0;
    unsigned int i = 0;
    if((pData.isNull()) || (Length < 4))
    {
        return 0;
    }
    for(i = 2; i < Length; i++)
    {
        chk1 = chk1 + pData.at(i);
        chk2 = chk2 + chk1;
    }

    chk1 = chk1 & 0xFF;
    chk2 = chk2 & 0xFF;
    QByteArray ba;
    ba.resize(2);
    ba[0] = chk1;
    ba[1] = chk2;
    return ba;
    //return (chk1 | (chk2 << 8 ));
}

void MyModBus::correctDateTime(QDateTime dateTime)
{
        if (dateTime.date().year() > 2038) {
        return;  // 如果超过2038年，则直接返回不执行时间设置
    }
    QString command = QString("date -s '%1' > /dev/null").arg(dateTime.toString("yyyy-MM-dd hh:mm:ss"));
    //int res =QProcess::execute(command);
    //qDebug()<<res;
    system(command.toLatin1().data());
    system("hwclock --systohc");
    //QString date = QString("date -s \"%1\"").arg(dateTime);
//    QStringList arg;

//    //soft
//    arg << "-s" << dateTime;
//    QProcess::execute("date", arg);

//    //rtc0
//    arg.clear();
//    arg << "-w";
//    QProcess::execute("hwclock", arg);

//    //rtc1
//    arg.clear();
//    arg << "-w" << "-f" << "/dev/rtc1";
//    QProcess::execute("hwclock", arg);

//    arg.clear();
//    arg << "--rtc=/dev/rtc1" << "--hctosys";
//    QProcess::execute("hwclock", arg);
//    QString qstrDateTime = QString("/bin/sh -c echo \"%1\" | sudo -S date \"%2\"").arg("ubuntu").arg(dateTime);
//    qDebug()<<qstrDateTime;
//    QProcess::execute(qstrDateTime);
//    QString qstrSaveTime = QString("/bin/sh -c echo \"%1\" | sudo -S hwclock --systohc").arg("ubuntu");
//    QProcess::execute(qstrSaveTime);
    //system("hwclock -w");
    //system("sync");
}
//int tempId=0;
//The reuslt 2 bytes checksum sequence would be {chk1, chk2}.
/*
void MyModBus::sendDataBy4g()
{
    while(!isClosed)
    {
        try
        {
            if(m_autoSave == 1)
            {
                QDateTime dateTime0= QDateTime::currentDateTime();//获取系统当前的时间
                QString str0 = dateTime0.toString("yyyy-MM-dd hh:mm:ss");//格式化时间
                if(m_weight_new.length()>0)
                {
                    int mode = 0;
                    if(m_currentMode == 1)  //累加模式，非正常模式。
                    {
                        mode = 7;   //哦哦
                    }
                    saveWeight(str0, m_weight_new.toDouble(), m_unit, mode, 1);
                    //qDebug()<<str0;

                }
            }
            QThread::msleep(m_saveInterval*1000);   //哦哦 对应常规设置->保存间隔[s]。
        }
        catch (std::exception &e) {
            //qDebug() << "Exception caught: " << e.what();
        } catch (...) {
            //qDebug() << "Unknown exception caught.";
        }
        malloc_trim(0);
    }
}*/

void MyModBus::sendDataBy4g()
{
    QElapsedTimer IntervalTimer;
    int rcvtime = 1;
    int mqtterrcount=0;
    #define MQTTRETRYTIME 3
    IntervalTimer.start();
    #if DEBUG_4G
    qDebug()<<"4G start";
    #endif
    change4gport = true;
    reconnect4g = true;
    while(!isClosed)
    {
        try
        {
            if (change4gport)
            {
                connect4g();
                if(m_4gConnStatus)
                {
                    change4gport = false;
                }
            }            
            else if(reconnect4g)
            {
                restart4g(true);
                QThread::msleep(6000);  //原值为2000。
                config4g();
                configGPS();
                reconnect4g = false;
            }
            else if(busyflag4g)
            {
                disconnect(serialPort4g,SIGNAL(readyRead()),this,SLOT(read4gData()));
                disconnect(serialPort4g,SIGNAL(readyRead()),this,SLOT(readGPSData()));
                bool step1 = sendOTACommandQICSGP();
                if(step1)
                {
                    bool step2 = sendOTACommandQIACT();
                    if(step2)
                    {
                        bool step3 = sendOTACommandQHTTPCFG();
                        if(step3)
                        {
                            bool step4 = false;
                            int count=-1;
                            while(++count < 3 && !step4)
                            {
                                step4 = sendOTACommandQHTTP();
                            }
                            if(step4)
                            {
                                bool step5 = UnzipOTAPackage();
                                if(step5)
                                {
                                    otaresult = true;
                                }
                            }
                        } 
                    }
                }
                connect(serialPort4g,SIGNAL(readyRead()),this,SLOT(read4gData()));
                busyflag4g=false;
            }
            if(!busyflag4g)
            {
                if(IntervalTimer.elapsed()>m_saveInterval*1000-1100)
                {
                    IntervalTimer.restart();
                    if(m_4gConnStatus)
                    {
                        rcvtime = 1;                        
                        sendCommand("ATE0\r\n");
                        QThread::msleep(100);
                        QElapsedTimer t;
                    #if GPS_4G_IS_ONE 
                        getGPS = false;
                        sendCommand("AT+QGPSGNMEA=\"GGA\"\r\n");
                        t.start();
                        while ((!getGPS) && (t.elapsed()<300)) {
                            QThread::msleep(100);
                            sendCommand("\r\n");
                        }
                    #endif
                        m_get4gSignal = false;
                        sendCommand("AT+CSQ\r\n");
                        t.restart();
                        while (!m_get4gSignal && t.elapsed()<300) {
                            QThread::msleep(50);
                            sendCommand("\r\n");
                        }
                        //查询系统时间
                        m_getclk = false;
                        sendCommand("AT+CCLK?\r\n");
                        t.restart();
                        while (!m_getclk && t.elapsed()<300) {
                            QThread::msleep(50);
                            sendCommand("\r\n");
                        }
                    }

                    if(m_autoSave == 1)
                    {  

                        // 生成一个新的GUID
                        QUuid id = QUuid::createUuid();
                        QString strId = id.toString(QUuid::WithoutBraces);
                        QDateTime dateTime0= QDateTime::currentDateTime();//获取系统当前的时间
                        QString str0 = dateTime0.toString("yyyy-MM-dd hh:mm:ss");//格式化时间
                        QString truckNo = m_truckNo;
                        if(m_weight_new.length()>0)
                        {
                            int mode = 0;
                            if(m_currentMode == 1)  //累加模式，非正常模式。
                            {
                                mode = 7;   //哦哦
                            }
                            saveCollectData(str0, m_weight_new.toDouble(), m_unit, m_lon,m_lon_dir, m_lat,m_lat_dir,m_height,m_height_unit, truckNo, strId, m_lon_o, m_lat_o, mode, 1);
                            if(m_4gConnStatus)
                            {
                                if(m_mqttSwitch == 1)
                                {
                                    /*尝试发送3次，如果都失败，则重启DTU-4G板。
                                    */
                                    if(m_openMqttClient&&m_connectMqttClient&&m_subSuccess)
                                    {
                                        mqtterrcount ++;
                                        for(int i=0;i<3;i++)
                                        {
                                            if(0 == send4gData(str0, m_weight_new, m_unit, m_lon_o,m_lon_dir, m_lat_o,m_lat_dir,m_height,m_height_unit, strId))
                                            {
                                                mqtterrcount = 0;
                                                break;
                                            }
                                        }
                                        if(mqtterrcount >= MQTTRETRYTIME)
                                        {
                                            mqtterrcount = 0;
                                            reconnect4g = true;
                                            #if DEBUG_4G
                                            qDebug()<<"4G restart";
                                            #endif
                                        }
                                    }
                                    else
                                    {
                                        mqtterrcount ++;
                                        #if DEBUG_4G
                                        qDebug()<<"mqtt connect error";
                                        #endif
                                        if(mqtterrcount >= MQTTRETRYTIME)
                                        {
                                            mqtterrcount = 0;
                                            reconnect4g = true;
                                            #if DEBUG_4G
                                            qDebug()<<"4G restart";
                                            #endif
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if(IntervalTimer.elapsed()>rcvtime*500)
                {
                    rcvtime=(IntervalTimer.elapsed()/500)+1;
                    sendCommand("\r\n");
                    #if GPS_4G_IS_ONE == 0
                    if(rcvtime>4 && (rcvtime%2==0))
                    {
                        if(m_4gConnStatus)
                        {
                            switchToGPS(1);
                            for (uint8_t i = 0; i < 2; i++)
                            {
                                QThread::msleep(91); 
                                sendGPSCommand("\r\n");
                                QThread::msleep(10);                                
                            }
                            switchToGPS(0);
                        }
                    }
                    #endif
                }
            }
        }
        catch (std::exception &e) {
            //qDebug() << "Exception caught: " << e.what();
        }
        catch (...) {
            //qDebug() << "Unknown exception caught.";
        }
        malloc_trim(0);
    }
}
//int arrCount=0;
int MyModBus::send4gData(QString str0, QString weight, QString unit, double lon, QString lonDir, double lat, QString latDir, double height, QString heightUnit, QString id)
{
    QJsonObject jsonObj;
    jsonObj.insert("id", id);
    jsonObj.insert("dateTime", str0);
    if(weight.length() > 0)
    {
        QJsonArray jsonDatas;
        QJsonObject jsonData;
        jsonData.insert("type", "weight");
        jsonData.insert("unitType", unit);
        jsonData.insert("value", weight);
        //jsonData.insert("value", QString::number(tempId));
        //jsonData.insert("remark","");
        jsonDatas.append(jsonData);
        jsonObj.insert("datas", jsonDatas);
    }
    if(lon > std::numeric_limits<double>::lowest()
        || lat > std::numeric_limits<double>::lowest()
        || height > std::numeric_limits<double>::lowest())
    {
        QJsonArray jsonGPS;
        if(lon > std::numeric_limits<double>::lowest())
        {
            QJsonObject jsonLon;
            double tmp_lon = lon;
            if(lonDir.trimmed() == "W")
            {
                tmp_lon = lon * -1;
            }
            jsonLon.insert("type","longitude");
            jsonLon.insert("value",QString::number(tmp_lon));
            jsonGPS.append(jsonLon);
        }
        if(lat > std::numeric_limits<double>::lowest())
        {
            QJsonObject jsonLat;
            double tmp_lat = lat;
            if(latDir.trimmed() == "S")
            {
                tmp_lat = lat * -1;
            }
            jsonLat.insert("type","latitude");
            jsonLat.insert("value",QString::number(tmp_lat));
            jsonGPS.append(jsonLat);
        }
        if(height > std::numeric_limits<double>::lowest())
        {
            QJsonObject jsonHeight;
            jsonHeight.insert("type","height");
            jsonHeight.insert("unitType",heightUnit.toLower());
            jsonHeight.insert("value",QString::number(height));
            jsonGPS.append(jsonHeight);
        }
        jsonObj.insert("gps", jsonGPS);
    }

    if(arrToSend.count()>100)
    {
        arrToSend.removeFirst();
    }

    arrToSend.append(jsonObj);      //将QJsonObject对象追加到QJsonArray。

//    if(reconnect4g)
//    {
//        qDebug()<<"send err:4G disconnect\r\n";
//        return -1;
//    }

//    /*这种复位机制好吗？至少不及时。
//     *如果
//    */
//    if(arrToSend.count() > 5)
//    {
//        reconnect4g = true;
//        restart4g(true);
//        QThread::msleep(2000);
//        config4g();
//        //configGPS();
//        reconnect4g = false;
//    }
    /*只发送当前数据。
     * a. 序列化待发送数据，得到jsonObjStr2。注意，这里有些不对，因为jsonObjStr2是QString，不是字节数据流。
    */
    QJsonArray jsonDatas;
    jsonDatas.append(jsonObj);
    //qDebug()<<jsonDatas.count();
    QJsonDocument jsonDoc2(jsonDatas);      //这么写，序列化后最外面是[]。如果放入的是JsonObject,
    QString jsonObjStr2= jsonDoc2.toJson(QJsonDocument::Compact).simplified();
    int lenToSend= jsonObjStr2.length();

    //qDebug()<<lenToSend<<"StrToSend:"<<jsonObjStr2;        //OK

    QElapsedTimer t2;


    QString pubCmd2 = QString("AT+QMTPUBEX=0,0,0,0,\"%1\",%2\r\n")
                         .arg(m_topic)
                         .arg(lenToSend);
    //qDebug()<<"ATCMD:"<<pubCmd2;
    //QThread::msleep(100);

    m_continueSend=false;
    sendCommand(pubCmd2);

    t2.start();

    while(!m_continueSend && t2.elapsed() < 1000) //原值500
    {
        //QCoreApplication::processEvents();
        QThread::msleep(10);
    }

    if(!m_continueSend){
        //没有受到'>'提示符。
        #if DEBUG_4G
        qDebug()<<"err:4G >";
        #endif
        return -1;
    }

    //受到4G模块输出的>提示符，向模块发送指定长度的字节数据。
    pub = false;
    sendCommand(jsonObjStr2+"\r\n");
    //qDebug()<<"DATA:"<<jsonObjStr2;

    while(!pub && t2.elapsed() < 1100){
        //QCoreApplication::processEvents();
        QThread::msleep(100);
        sendCommand("\r\n");
    }

    if(!pub){
        //没有受到'>'提示符。
        #if DEBUG_4G
        qDebug()<<"err:4G pub";
        #endif
        return -1;
    }
    #if DEBUG_4G
    qDebug()<<"4G pub OK";
    #endif  

    return 0;

    /*
    //以下作废。
    QJsonDocument doc(arrToSend);
    QByteArray jsonData = doc.toJson(); // 序列化到JSON字符串或字节数组
    QJsonDocument copiedDoc = QJsonDocument::fromJson(jsonData); // 反序列化，自动深拷贝
    QJsonArray temp = copiedDoc.array();

    int count = arrToSend.count()>m_mqttInterval?m_mqttInterval:arrToSend.count();

    for (int i = 0; i < count; i++)
    {
        QJsonArray arr;
        //for(int j=0; j < groupSize && (i*groupSize+j)< arrToSend.count();j++)
        {
            arr.append(temp.at(i).toObject());
        }
//        if(arr.count()==0)
//        {
//            return;
//        }
        //QString jsonObjStr =QString(QJsonDocument(jsonObj).toJson()).simplified();
        QJsonDocument jsonDoc = QJsonDocument(arr);
        QString jsonObjStr =jsonDoc.toJson(QJsonDocument::Compact).simplified();

        int length = jsonObjStr.length();

        QElapsedTimer t;
        pub = false;
        //AT+QMTPUBEX=0,0,0,0,"topic/pub",30
        QString pubCmd = QString("AT+QMTPUBEX=0,0,0,0,\"%1\",%2\r\n")
                             .arg(m_topic)
                             .arg(length);
        m_continueSend=false;
        sendCommand(pubCmd);
        t.start();
        //serialPort4g->waitForReadyRead(500);
        //QThread::msleep(100);
        qDebug()<<arr.count();
        while(!m_continueSend && t.elapsed() < 1000) //原值500
        {
            //QCoreApplication::processEvents();
            QThread::msleep(10);
        }
        sendCommand(jsonObjStr+"\r\n");
        qDebug()<<jsonObjStr;
        //serialPort4g->waitForReadyRead(500);
        //QThread::msleep(100);
        while(!pub && t.elapsed() < 1100){
            //QCoreApplication::processEvents();
            QThread::msleep(10);
        }
    }

    return 0;*/
}
//int arrCount=0;
/*
void MyModBus::send4gData(QString str0, QString weight, QString unit, double lon, QString lonDir, double lat, QString latDir, double height, QString heightUnit, QString truckNo, QString id)
{
    QJsonObject jsonObj;
    jsonObj.insert("id", id);
    jsonObj.insert("dateTime", str0);
    if(weight.length() > 0)
    {
        QJsonArray jsonDatas;
        QJsonObject jsonData;
        jsonData.insert("type", "weight");
        jsonData.insert("unitType", unit);
        jsonData.insert("value", weight);
        //jsonData.insert("value", QString::number(tempId));
        //jsonData.insert("remark","");
        jsonDatas.append(jsonData);
        jsonObj.insert("datas", jsonDatas);
    }
    if(m_lon > std::numeric_limits<double>::min()
        || m_lat > std::numeric_limits<double>::min()
        || m_height > std::numeric_limits<double>::min())
    {
        QJsonArray jsonGPS;
        if(m_lon > std::numeric_limits<double>::min())
        {
            QJsonObject jsonLon;
            double lon = m_lon;
            if(m_lon_dir.trimmed() == "W")
            {
                lon = m_lon * -1;
            }
            jsonLon.insert("type","longitude");
            jsonLon.insert("value",QString::number(lon));
            jsonGPS.append(jsonLon);
        }
        if(m_lat > std::numeric_limits<double>::min())
        {
            QJsonObject jsonLat;
            double lat = m_lat;
            if(m_lat_dir.trimmed() == "S")
            {
                lat = m_lat * -1;
            }
            jsonLat.insert("type","latitude");
            jsonLat.insert("value",QString::number(lat));
            jsonGPS.append(jsonLat);
        }
        if(m_height > std::numeric_limits<double>::min())
        {
            QJsonObject jsonHeight;
            jsonHeight.insert("type","height");
            jsonHeight.insert("unitType",m_height_unit.toLower());
            jsonHeight.insert("value",QString::number(m_height));
            jsonGPS.append(jsonHeight);
        }
        jsonObj.insert("gps", jsonGPS);
    }

    if(arrToSend.count()>100)
    {
        arrToSend.removeFirst();
    }

    arrToSend.append(jsonObj);

    if(arrToSend.count() > 5)
    {
        restart4g(true);
        QThread::msleep(2000);
        config4g();
        configGPS();
    }

    if(reconnect4g)
    {
        return;
    }
    QJsonDocument doc(arrToSend);
    QByteArray jsonData = doc.toJson(); // 序列化到JSON字符串或字节数组
    QJsonDocument copiedDoc = QJsonDocument::fromJson(jsonData); // 反序列化，自动深拷贝
    QJsonArray temp = copiedDoc.array();

    int count = arrToSend.count()>m_mqttInterval?m_mqttInterval:arrToSend.count();
    int groupSize=1;
    for (int i = 0; i < qCeil(count/static_cast<float>(groupSize)); i++)
    {
        QJsonArray arr;
        for(int j=0; j < groupSize && (i*groupSize+j)< arrToSend.count();j++)
        {
            arr.append(temp.at(i*groupSize+j).toObject());
        }
        if(arr.count()==0)
        {
            return;
        }
        //QString jsonObjStr =QString(QJsonDocument(jsonObj).toJson()).simplified();
        QJsonDocument jsonDoc = QJsonDocument(arr);
        QString jsonObjStr =jsonDoc.toJson(QJsonDocument::Compact).simplified();

        int length = jsonObjStr.length();

        QElapsedTimer t;
        t.start();
        pub = false;
        //AT+QMTPUBEX=0,0,0,0,"topic/pub",30
        QString pubCmd = QString("AT+QMTPUBEX=0,0,0,0,\"%1\",%2\r\n")
                             .arg(m_topic)
                             .arg(length);
        m_continueSend=false;
        sendCommand(pubCmd);
        //serialPort4g->waitForReadyRead(500);
        //QThread::msleep(100);
        qDebug()<<arr.count();
        while(!m_continueSend && t.elapsed() < 500)
        {
            QCoreApplication::processEvents();
        }
        sendCommand(jsonObjStr+"\r\n");
        qDebug()<<jsonObjStr;
        //serialPort4g->waitForReadyRead(500);
        //QThread::msleep(100);
        while(!pub && t.elapsed() < 1000){
            QCoreApplication::processEvents();
        }
    }
}*/

bool MyModBus::saveCollectData(QString str0, double weight, QString unit, double lon, QString lonDir, double lat, QString latDir, double height, QString heightUnit, QString truckNo, QString id, double lon_o, double lat_o,int mode, int scheduled)
{
    bool result = false;

    QDateTime dateTime= QDateTime::currentDateTime().addDays(-3);//获取系统当前的时间
    QString str = dateTime .toString("yyyy-MM-dd hh:mm:ss");//格式化时间
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QSqlQuery* query = new QSqlQuery(m_db);

    query->exec(QString("DELETE FROM weightTable WHERE createdTime < '%1'").arg(str));
    query->clear();

    QString queryser= QString("INSERT INTO weightTable (id, weight, weightUnit, lon, lonDir, lat, latDir, height, heightUnit, truckNo, createdTime, lon_o, lat_o, mode, scheduled) VALUES ('%1', %2, '%3', %4, '%5', %6, '%7', %8, '%9', '%10', '%11', %12, %13, %14, %15);")
                           .arg(id)
                           .arg(weight)
                           .arg(unit)
                           .arg(lon)
                           .arg(lonDir)
                           .arg(lat)
                           .arg(latDir)
                           .arg(height)
                           .arg(heightUnit)
                           .arg(truckNo)
                           .arg(str0)
                           .arg(lon_o)
                           .arg(lat_o)
                           .arg(mode)
                           .arg(scheduled);
    if(query->exec(queryser))
    {
        result = true;
    }
    else
    {
        qDebug()<<query->lastError();
    }
    delete query;
    query = nullptr;
    //db.close();
    return result;
}
/*
bool MyModBus::saveWeightAndAngle(QString str0, double weight, QString unit, double angle)
{
    bool result = false;

    QDateTime dateTime= QDateTime::currentDateTime().addDays(-3);//获取系统当前的时间
    QString str = dateTime .toString("yyyy-MM-dd hh:mm:ss");//格式化时间
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QSqlQuery* query = new QSqlQuery(m_db);

    query->exec(QString("DELETE FROM weightTable WHERE createdTime < '%1'").arg(str));
    query->clear();

    QString queryser= QString("INSERT INTO weightTable (weight, weightUnit, angle) VALUES (%1, '%2', %3);")
                           .arg(weight)
                           .arg(unit)
                           .arg(angle);
    if(query->exec(queryser))
    {
        result = true;
    }
    else
    {
        qDebug()<<query->lastError();
    }
    delete query;
    query = nullptr;
    //db.close();
    return result;
}*/

bool MyModBus::saveWeight(QString str0, double weight, QString unit, int mode, int scheduled)
{
    bool result = false;

    QDateTime dateTime= QDateTime::currentDateTime().addDays(-1*m_saveDays);//获取系统当前的时间
    QString str = dateTime .toString("yyyy-MM-dd hh:mm:ss");//格式化时间
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QSqlQuery* query = new QSqlQuery(m_db);

    query->exec(QString("DELETE FROM weightTable WHERE createdTime < '%1'").arg(str));
    query->clear();

    QString queryser= QString("INSERT INTO weightTable (createdTime, weight, weightUnit, mode, scheduled) VALUES ('%3', %1, '%2', %4, %5);")
                           .arg(weight)
                           .arg(unit)
                           .arg(str0)
                           .arg(mode)
                           .arg(scheduled);
    if(query->exec(queryser))
    {
        result = true;
    }
    else
    {
        qDebug()<<query->lastError();
    }
    delete query;
    query = nullptr;
    //db.close();
    return result;
}

bool MyModBus::saveCurrentWeight(QString weight, QString unit)
{
    QDateTime dateTime0= QDateTime::currentDateTime();//获取系统当前的时间
    QString str0 = dateTime0.toString("yyyy-MM-dd hh:mm:ss");//格式化时间
    int mode = 0;
    if(m_currentMode == 1)
    {
        mode = 7;
    }
    return saveWeight(str0, weight.toDouble(), unit, mode, -1);
}

//QVector<double> MyModBus::leastSquaresFit(const QVector<double> x, const QVector<double> y, int order)
//{
//    int n = x.size();
//    QVector<double> coefficients(order + 1, 0.0);
//    QVector<double> sum_x(2 * order + 1, 0.0);
//    QVector<double> sum_y(order + 1, 0.0);

//    for (int i = 0; i < n; i++)
//    {
//        double xi = x[i], yi = y[i];
//        for (int j = 0; j <= 2 * order; j++)
//        {
//            sum_x[j] += pow(xi, j);
//        }
//        for (int j = 0; j <= order; j++)
//        {
//            sum_y[j] += pow(xi, j) * yi;
//        }
//    }

//    MatrixXd A(order + 1, order + 1);

//    QVector<double> A((order + 1)*(order + 1), 0.0);

//    QVector<double> B(order + 1, 0.0);

//    for (int i = 0; i <= order; i++)
//    {
//        for (int j = 0; j <= order; j++)
//        {
//            A(i, j) = sum_x[i + j];
//        }
//        B[i] = sum_y[i];
//    }

//    QVector<double> X = A.colPivHouseholderQr().solve(B);
//    for (int i = 0; i <= order; i++)
//    {
//        coefficients[i] = X[i];
//    }

//    return coefficients;
//}

void MyModBus::refreshData()
{
    while(!isClosed)
    {
        refreshWeight();
        QThread::msleep(m_collectTime);
    }
}

void MyModBus::refreshVokltageData()
{
    while(!isClosed)
    {
        getVoltage();
        QThread::msleep(m_collectTime);
    }
}

bool MyModBus::setSendStatus(QString id)
{
    bool result = false;
    if(!m_db.isOpen()){
        m_db.open();
    }
    QString queryser= QString("UPDATE weightTable SET isSend = 1 WHERE id = '%1';")
                           .arg(id);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    //db.close();
    result = true;
    return result;
}

void MyModBus::sendArrRemoveObject(QString id)
{
    for(int i=0; i<arrToSend.count();++i)
    {
        QJsonObject rootObj = arrToSend.at(i).toObject();  // 转化为root对象

        QJsonValue rootValue = rootObj.value("id");  // 获取指定key对应的value,
        QString _id = rootValue.toString();
        if(_id == id)
        {
            arrToSend.removeAt(i);
        }
    }
}
void MyModBus::getWeight()
{
    if((!modbusDevice)||(modbusDevice->state() != QModbusDevice::ConnectedState))
    {
        return;
    }

    if(showSumWeight)   //哦 累加模式。
    {
        sumWeights();
    }
    else
    {
        bool replyFinished= false;
        QModbusReply *reply = modbusDevice->sendReadRequest(readRequest(0, 24), m_sensorSlaveID);   //哦哦 m_sensorSlaveID:从机地址
        if (reply) {    //哦哦 发送成功。
            if (!reply->isFinished())   //哦哦 未完成状态，则等待。
            {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                    replyFinished=true;
                    eventLoop.quit();
                });
                QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
                eventLoop.exec();
            } else {
                replyFinished=true;
            }
            if(replyFinished)
            {
                readWeight(reply);      //哦哦 modbus发送成功，且受到应答。
            }
            //reply->deleteLater();
            delete reply;
            reply = nullptr;
        }
        if(m_currentMode == 1)      //累加模式，非“正常模式”。
        {
            if(m_accumulateMode == 1)
            {
                if(m_stable == 1)
                {
                    if(m_weight_new.toDouble()<= m_accumulateZero)
                    {
                        if(m_maxWeight > std::numeric_limits<double>::lowest())
                        {
                            m_accumulateWeights.append(m_maxWeight);

                            saveWeight(m_maxWeightTime, m_maxWeight, m_unit, 2, 0);
                            m_maxWeight = std::numeric_limits<double>::lowest();
                        }
                    }
                    else if(m_weight_new.toDouble() > m_maxWeight && m_weight_new.toDouble() > m_accumulateZero)
                    {
                        m_maxWeight = m_weight_new.toDouble();
                        QDateTime dateTime0= QDateTime::currentDateTime();//获取系统当前的时间
                        m_maxWeightTime = dateTime0.toString("yyyy-MM-dd hh:mm:ss");//格式化时间
                    }
                }
            }
        }
    }

}

int MyModBus::getDecimalPlaces()
{
    //int temp = 0;
    if(!modbusDevice)
    {
        return 0;
    }
    auto *reply = modbusDevice->sendReadRequest(readRequest(18, 1), m_sensorSlaveID);
    bool replyFinished = false;
    if (reply) {

        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        } else {
            replyFinished=true;
        }
    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        return 0;
    }
    if(replyFinished)
    {
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 1)
            {
                m_decimalPlaces =unit.value(0);
                //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
                //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
                emit decimalPlacesChanged(m_decimalPlaces);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }
    }
    delete reply;
    reply = nullptr;
    return m_decimalPlaces;
}

int MyModBus::getMinGraduation()
{
//    if(!modbusDevice)
//    {
//        return;
//    }
//    if (auto *reply = modbusDevice->sendReadRequest(readRequest(19, 1), m_slaveID)) {
//        if (!reply->isFinished())
//        {
//            connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadMinGraduation);
//        } else {
//            delete reply;
//        }

//    }
//    else
//    {
//        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
//    }
    if(!modbusDevice)
    {
        return -1;
    }
    auto *reply = modbusDevice->sendReadRequest(readRequest(19, 1), m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
            //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadMinGraduation);
        } else {
            //reply->deleteLater();
        }

    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        return -1;
    }
    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_minGraduation = unit.value(0);
            //reply->deleteLater();
            delete reply;
            reply = nullptr;
            return unit.value(0);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return -1;
}
void MyModBus::slotReadWeight(int i)
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 3)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            int _weight= byteArrayToInt(arry);
            int _decimal;
            switch(i)
            {
            case 0:
                _decimal = m_decimalPlaces0;
                m_voltage0 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                emit voltage0Changed(m_voltage0);
                if(m_weight.contains(QString::number(i)))
                {
                    m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                }
                else
                {
                    m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                }
                m_stable0=unit.value(2)&1;
                m_normal0=(unit.value(2)>>1)&1;
                m_zero0=(unit.value(2)>>2)&1;
                m_positive0=(unit.value(2)>>3)&1;
                break;
            case 1:
                _decimal = m_decimalPlaces1;
                m_voltage1 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                emit voltage1Changed(m_voltage1);
                if(m_weight.contains(QString::number(i)))
                {
                    m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                }
                else
                {
                    m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                }
                m_stable1=unit.value(2)&1;
                m_normal1=(unit.value(2)>>1)&1;
                m_zero1=(unit.value(2)>>2)&1;
                m_positive1=(unit.value(2)>>3)&1;
                break;
            case 2:
                _decimal = m_decimalPlaces2;
                m_voltage2 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                emit voltage2Changed(m_voltage2);
                if(m_weight.contains(QString::number(i)))
                {
                    m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                }
                else
                {
                    m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                }
                m_stable2=unit.value(2)&1;
                m_normal2=(unit.value(2)>>1)&1;
                m_zero2=(unit.value(2)>>2)&1;
                m_positive2=(unit.value(2)>>3)&1;
                break;
            case 3:
                _decimal = m_decimalPlaces3;
                m_voltage3 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                emit voltage3Changed(m_voltage3);

                if(m_weight.contains(QString::number(i)))
                {
                    m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                }
                else
                {
                    m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                }
                m_stable3=unit.value(2)&1;
                m_normal3=(unit.value(2)>>1)&1;
                m_zero3=(unit.value(2)>>2)&1;
                m_positive3=(unit.value(2)>>3)&1;
                break;
            case 4:
                _decimal = m_decimalPlaces4;
                m_voltage4 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                emit voltage4Changed(m_voltage4);

                if(m_weight.contains(QString::number(i)))
                {
                    m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                }
                else
                {
                    m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                }
                m_stable4=unit.value(2)&1;
                m_normal4=(unit.value(2)>>1)&1;
                m_zero4=(unit.value(2)>>2)&1;
                m_positive4=(unit.value(2)>>3)&1;
                break;
            case 5:

                _decimal = m_decimalPlaces5;
                m_voltage5 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                emit voltage5Changed(m_voltage5);

                if(m_weight.contains(QString::number(i)))
                {
                    m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                }
                else
                {
                    m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                }
                m_stable5=unit.value(2)&1;
                m_normal5=(unit.value(2)>>1)&1;
                m_zero5=(unit.value(2)>>2)&1;
                m_positive5=(unit.value(2)>>3)&1;
                break;
            case 6:
                _decimal = m_decimalPlaces6;
                m_voltage6 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                emit voltage6Changed(m_voltage6);

                if(m_weight.contains(QString::number(i)))
                {
                    m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                }
                else
                {
                    m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                }
                m_stable6=unit.value(2)&1;
                m_normal6=(unit.value(2)>>1)&1;
                m_zero6=(unit.value(2)>>2)&1;
                m_positive6=(unit.value(2)>>3)&1;
                break;
            case 7:
                _decimal = m_decimalPlaces7;
                m_voltage7 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                emit voltage7Changed(m_voltage7);

                if(m_weight.contains(QString::number(i)))
                {
                    m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                }
                else
                {
                    m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                }
                m_stable7=unit.value(2)&1;
                m_normal7=(unit.value(2)>>1)&1;
                m_zero7=(unit.value(2)>>2)&1;
                m_positive7=(unit.value(2)>>3)&1;
                break;
            }
            //m_sensorLastRevTime= QDateTime::currentDateTime();//获取系统当前的时间
            setSensorLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));//格式化时间

        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadVoltage(int i)
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;

            switch(i)
            {
                case 0:
                    m_voltage0 = QString::number(byteArrayToInt(arry));
                    emit voltage0Changed(m_voltage0);
                    break;
                case 1:
                    m_voltage1 = QString::number(byteArrayToInt(arry));
                    emit voltage1Changed(m_voltage1);
                    break;
                case 2:
                    m_voltage2 = QString::number(byteArrayToInt(arry));
                    emit voltage2Changed(m_voltage2);
                    break;
                case 3:
                    m_voltage3 = QString::number(byteArrayToInt(arry));
                    emit voltage3Changed(m_voltage3);
                    break;
                case 4:
                    m_voltage4 = QString::number(byteArrayToInt(arry));
                    emit voltage4Changed(m_voltage4);
                    break;
                case 5:
                    m_voltage5 = QString::number(byteArrayToInt(arry));
                    emit voltage5Changed(m_voltage5);
                    break;
                case 6:
                    m_voltage6 = QString::number(byteArrayToInt(arry));
                    emit voltage6Changed(m_voltage6);
                    break;
                case 7:
                    m_voltage7 = QString::number(byteArrayToInt(arry));
                    emit voltage7Changed(m_voltage0);
                    break;
            }
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadDecimalPlaces()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_decimalPlaces =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit decimalPlacesChanged(m_decimalPlaces);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadDecimalPlaces(int i)
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            switch(i)
            {
                case 0:
                    m_decimalPlaces0 =unit.value(0);
                    break;
                case 1:
                    m_decimalPlaces1 =unit.value(0);
                    break;
                case 2:
                    m_decimalPlaces2 =unit.value(0);
                    break;
                case 3:
                    m_decimalPlaces3 =unit.value(0);
                    break;
                case 4:
                    m_decimalPlaces4 =unit.value(0);
                    break;
                case 5:
                    m_decimalPlaces5 =unit.value(0);
                    break;
                case 6:
                    m_decimalPlaces6 =unit.value(0);
                    break;
                case 7:
                    m_decimalPlaces7 =unit.value(0);
                    break;
            }

            //emit decimalPlacesChanged(m_decimalPlaces);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadMinGraduation()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_minGraduation =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit minGraduationChanged(m_minGraduation);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadSteadyStateFiltering()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_steadyStateFiltering =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit steadyStateFilteringChanged(m_steadyStateFiltering);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadDigitalFiltering()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_digitalFiltering =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit digitalFilteringChanged(m_digitalFiltering);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadStabilityRange()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_stabilityRange =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit stabilityRangeChanged(m_stabilityRange);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadClearRange()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_clearRange =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit clearRangeChanged(m_clearRange);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPowerAutoZero()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_powerAutoZero =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit powerAutoZeroChanged(m_powerAutoZero);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadZeroTraceRange()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_zeroTraceRange =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit zeroTraceRangeChanged(m_zeroTraceRange);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadADSampleRate()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_aDSampleRate =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit aDSampleRateChanged(m_aDSampleRate);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadMaxRange()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_maxRange= byteArrayToInt(arry);
            emit maxRangeChanged(m_maxRange);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadHoldMode()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_holdMode =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit holdModeChanged(m_holdMode);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadHoldTriggerCondition()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_holdTriggerCondition =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit holdTriggerConditionChanged(m_holdTriggerCondition);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadZeroValue()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_zeroValue= byteArrayToInt(arry);
            emit zeroValueChanged(m_zeroValue);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadHoldResult()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_holdResult= byteArrayToInt(arry);
            emit holdResultChanged(m_holdResult);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreIsStable1()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preIsStable1 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preIsStable1Changed(m_preIsStable1);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreMinDuration1()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preMinDuration1 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preMinDuration1Changed(m_preMinDuration1);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreCondition1()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preCondition1 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preCondition1Changed(m_preCondition1);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreValue11()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_preValue11= byteArrayToInt(arry);
            emit preValue11Changed(m_preValue11);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreValue21()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_preValue21= byteArrayToInt(arry);
            emit preValue21Changed(m_preValue21);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreIsStable2()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preIsStable2 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preIsStable2Changed(m_preIsStable2);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreMinDuration2()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preMinDuration2 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preMinDuration2Changed(m_preMinDuration2);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreCondition2()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preCondition2 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preCondition2Changed(m_preCondition2);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreValue12()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_preValue12= byteArrayToInt(arry);
            emit preValue12Changed(m_preValue12);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreValue22()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_preValue22= byteArrayToInt(arry);
            emit preValue22Changed(m_preValue22);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreIsStable3()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preIsStable3 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preIsStable3Changed(m_preIsStable3);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreMinDuration3()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preMinDuration3 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preMinDuration3Changed(m_preMinDuration3);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreCondition3()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preCondition3 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preCondition3Changed(m_preCondition3);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreValue13()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_preValue13= byteArrayToInt(arry);
            emit preValue13Changed(m_preValue13);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreValue23()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_preValue23= byteArrayToInt(arry);
            emit preValue23Changed(m_preValue23);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreValue24()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_preValue24= byteArrayToInt(arry);
            emit preValue24Changed(m_preValue24);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadStable()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_stable =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit stableChanged(m_stable);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}
void MyModBus::slotReadNormal()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_normal =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit normalChanged(m_normal);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}
void MyModBus::slotReadZero()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_zero =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit zeroChanged(m_zero);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}
void MyModBus::slotReadPositive()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_positive =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit positiveChanged(m_positive);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadCurrent0()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_current0= byteArrayToInt(arry);
            emit current0Changed(m_current0);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadVoltageData(int i)
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            int voltage= byteArrayToInt(arry);
            switch(i)
            {
                case 0:
                    m_voltage0_=voltage;
                        break;
                case 1:
                        m_voltage1_=voltage;
                    break;
                case 2:
                    m_voltage2_=voltage;
                        break;
                case 3:
                        m_voltage3_=voltage;
                    break;
                case 4:
                    m_voltage4_=voltage;
                        break;
                case 5:
                        m_voltage5_=voltage;
                    break;
                case 6:
                    m_voltage6_=voltage;
                        break;
                case 7:
                        m_voltage7_=voltage;
                    break;
            }
            //emit current0Changed(m_current0);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotbacklightChanged()
{
   setbacklightvalue(m_backlight);
}

bool MyModBus::setbacklightvalue(int value)
{
    QString cmd = "echo "+ QString::number(value) +" >" + "/sys/class/backlight/backlight/brightness";
    //qDebug() << cmd;
    int ret = system(qPrintable(cmd));
    if (ret != 0) 
    {
        qDebug() << "Backlight set value "+ QString::number(value) +" failed";
        return false;
    }
    if(value == 0)
    {
        volatile uint32_t* pwm_virt_base;
        pwm_virt_base = pwm_map_registers(PWM_PHYS_BASE, PWM_REG_SIZE);
        if (pwm_virt_base == NULL) {
        }
        if (pwm_set(pwm_virt_base+PWM_REG_OFFSET/4) != 0) {  //0x01C21400
        }
        pwm_unmap(pwm_virt_base, PWM_REG_SIZE);
    }
    return true;
}

void MyModBus::beep(int msecond)
{
    QFile brightnessFile("/sys/class/leds/pwm-buzzer/brightness");
    if (brightnessFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        QTextStream out(&brightnessFile);
        out << "100";
        brightnessFile.close();
    } else {
        qDebug() << "Failed to open brightness file";
        return;
    }
     // 停止任何可能正在运行的定时器
    timerbeep->stop();
    // 设置为单次触发模式
    timerbeep->setSingleShot(true);
    // 设置高精度属性
    timerbeep->setTimerType(Qt::PreciseTimer);
    // 设置间隔并启动
    timerbeep->setInterval(msecond);
    timerbeep->start();
    return ;
}

void MyModBus::BeepTimeOut()
{
    timerbeep->stop();
    // 快速关闭蜂鸣器（避免使用system函数）
    QFile brightnessFile("/sys/class/leds/pwm-buzzer/brightness");
    if (brightnessFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        QTextStream out(&brightnessFile);
        out << "1";
        brightnessFile.close();
    } else {
        qDebug() << "Failed to open brightness file";
    }
}

void MyModBus::slotReadCollectData()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 4)
        {
            m_stable =unit.value(0);
            emit stableChanged(m_stable);

            m_normal =unit.value(1);
            emit normalChanged(m_normal);

            m_zero =unit.value(2);
            emit zeroChanged(m_zero);

            m_positive =unit.value(3);
            emit positiveChanged(m_positive);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadCollectData_(int i)
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 4)
        {
            switch(i)
            {
                case 0:
                    m_stable0 =unit.value(0);
                    //emit stableChanged(m_stable);

                    m_normal0 =unit.value(1);
                    //emit normalChanged(m_normal);

                    m_zero0 =unit.value(2);
                    //emit zeroChanged(m_zero);

                    m_positive0 =unit.value(3);
                    //emit positiveChanged(m_positive);
                        break;
                case 1:
                    m_stable1 =unit.value(0);
                    //emit stableChanged(m_stable);

                    m_normal1 =unit.value(1);
                    //emit normalChanged(m_normal);

                    m_zero1 =unit.value(2);
                    //emit zeroChanged(m_zero);

                    m_positive1 =unit.value(3);
                    //emit positiveChanged(m_positive);
                    break;
                case 2:
                    m_stable2 =unit.value(0);
                    //emit stableChanged(m_stable);

                    m_normal2 =unit.value(1);
                    //emit normalChanged(m_normal);

                    m_zero2 =unit.value(2);
                    //emit zeroChanged(m_zero);

                    m_positive2 =unit.value(3);
                    //emit positiveChanged(m_positive);
                    break;
                case 3:
                    m_stable3 =unit.value(0);
                    //emit stableChanged(m_stable);

                    m_normal3 =unit.value(1);
                    //emit normalChanged(m_normal);

                    m_zero3 =unit.value(2);
                    //emit zeroChanged(m_zero);

                    m_positive3 =unit.value(3);
                    //emit positiveChanged(m_positive);
                    break;
                case 4:
                    m_stable4 =unit.value(0);
                    //emit stableChanged(m_stable);

                    m_normal4 =unit.value(1);
                    //emit normalChanged(m_normal);

                    m_zero4 =unit.value(2);
                    //emit zeroChanged(m_zero);

                    m_positive4 =unit.value(3);
                    //emit positiveChanged(m_positive);
                    break;
                case 5:
                    m_stable5 =unit.value(0);
                    //emit stableChanged(m_stable);

                    m_normal5 =unit.value(1);
                    //emit normalChanged(m_normal);

                    m_zero5 =unit.value(2);
                    //emit zeroChanged(m_zero);

                    m_positive5 =unit.value(3);
                    //emit positiveChanged(m_positive);
                    break;
                case 6:
                    m_stable6 =unit.value(0);
                    //emit stableChanged(m_stable);

                    m_normal6 =unit.value(1);
                    //emit normalChanged(m_normal);

                    m_zero6 =unit.value(2);
                    //emit zeroChanged(m_zero);

                    m_positive6 =unit.value(3);
                    //emit positiveChanged(m_positive);
                    break;
                case 7:
                    m_stable7 =unit.value(0);
                    //emit stableChanged(m_stable);

                    m_normal7 =unit.value(1);
                    //emit normalChanged(m_normal);

                    m_zero7 =unit.value(2);
                    //emit zeroChanged(m_zero);

                    m_positive7 =unit.value(3);
                    //emit positiveChanged(m_positive);
                    break;
            }

        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}


void MyModBus::slotCollectTimeChanged()
{
    timer->stop();
    timer->setInterval(m_collectTime);
    timer->start();
}

void MyModBus::slotEncoderIntervalChanged()
{
    timerEncoder->stop();
    timerEncoder->setInterval(m_encoderInterval);
    timerEncoder->start();
}

void MyModBus::slotReadNormalPara()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_digitalFiltering =unit.value(0);
            m_steadyStateFiltering =unit.value(1);
            m_decimalPlaces=unit.value(7);
            m_minGraduation=unit.value(8);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            //emit digitalFilteringChanged(m_digitalFiltering);
            emit normalParaRead();
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::readGPSData()
{
    setGpsLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    QByteArray buf;
    if (serialPort4g){

        buf = serialPort4g->readAll();

        if (!buf.isEmpty())
        {
            QString msg = QString::fromUtf8(buf);
            QStringList lst =msg.split("\r\n");
            for(int i = 0; i< lst.length(); i++)
            {
                if(lst[i].length() > 0)
                {
                    /*if(lst[i].startsWith("+QGPSGNMEA"))
                    {
                        if(lst[i].contains(":"))
                        {
                            int pos = lst[i].indexOf(":");
                            QString msg1 = lst[i].mid(pos + 1);
                            if(msg1.contains("$GNGGA"))
                            {
                                QStringList list = msg1.split(",");
                                if(list.length() > 11)
                                {
                                    getGPS = true;
                                    if(!list[4].isEmpty())
                                    {
                                        m_lon_o = list[4].toDouble();
                                        m_lon = list[4].toDouble();
                                        //m_lon = 10246.973877;
                                        int temp_lon = qFloor(m_lon/100);
                                        m_lon = temp_lon+(m_lon-temp_lon*100)/60;
                                    }
                                    m_lon_dir = list[5];

                                    if(!list[2].isEmpty())
                                    {
                                        m_lat_o = list[2].toDouble();
                                        m_lat = list[2].toDouble();
                                        //m_lat = 2458.928833;
                                        int temp_lat = qFloor(m_lat/100);
                                        m_lat = temp_lat+(m_lat-temp_lat*100)/60;
                                    }


                                    m_lat_dir = list[3];
                                    if(!list[9].isEmpty())
                                    {
                                        m_height = list[9].toDouble();
                                    }
                                    if(!list[10].isEmpty())
                                    {
                                        m_height_unit = list[10];
                                    }

                                    qDebug()<<"";
                                }
                            }
                        }
                    }*/

                    if(lst[i].contains("$GNGGA"))
                    {
                        QStringList list = lst[i].split(",");
                        if(list.length() > 11)
                        {
                            if(!list[4].isEmpty())
                            {
                                m_lon_o = list[4].toDouble();
                                m_lon = list[4].toDouble();
                                //m_lon = 10246.973877;
                                int temp_lon = qFloor(m_lon/100);
                                m_lon = temp_lon+(m_lon-temp_lon*100)/60;
                            }

                            if(!list[5].isEmpty())
                            {
                               m_lon_dir = list[5];
                            }

                            if(!list[2].isEmpty())
                            {
                               m_lat_o = list[2].toDouble();
                               m_lat = list[2].toDouble();
                               //m_lat = 2458.928833;
                               int temp_lat = qFloor(m_lat/100);
                               m_lat = temp_lat+(m_lat-temp_lat*100)/60;
                            }

                            if(!list[3].isEmpty())
                            {
                               m_lat_dir = list[3];
                            }

                            if(!list[9].isEmpty())
                            {
                                m_height = list[9].toDouble();
                            }
                            if(!list[10].isEmpty())
                            {
                                m_height_unit = list[10];
                            }
                            qDebug()<<"";
                        }
                    }

                }
            }

        }
        buf.clear();
    }
}

//修改read4gData()函数，使其只读取数据并异步处理
void MyModBus::read4gData()
{
    try
    {
        if(!serialPort4g)
        {
            return;
        }
        QByteArray buf = serialPort4g->readAll();//读取串口数据
        if(buf.isEmpty())
        {
            return;
        }
      
        // 处理'>'字符并设置标志
        if(buf.contains(">"))
        {
            buf.replace(">", "");
            m_continueSend = true;
        }
        
        // 使用QMutex保护buffer操作
        QMutexLocker locker(&mutex);
        buffer.append(buf);
        
        // 查找完整的行
        int pos = buffer.lastIndexOf("\r\n");
        if(pos > -1)
        {
            QByteArray temp = buffer.mid(0, pos+2);
            // 将数据复制到临时变量，以便在锁外使用
            QByteArray pendingData = temp;
            
            // 移除已处理的数据
            buffer.remove(0, pos+2);
            
            // 解锁后异步处理数据，避免长时间持有锁
            locker.unlock();
            
            // 使用Qt::QueuedConnection异步调用处理函数
            QMetaObject::invokeMethod(this, "processPendingData", 
                                     Qt::QueuedConnection, 
                                     Q_ARG(QByteArray, pendingData));
            
            // 重新加锁以便函数结束时正常解锁
            locker.relock();
        }
    }
    catch (std::exception &e)
    {
        //qDebug() << "Exception caught: " << e.what();
    } 
    catch (...)
    {
        //qDebug() << "Unknown exception caught.";
    }
}

//实现异步处理函数
void MyModBus::processPendingData(const QByteArray &data)
{
    try
    {
        // 处理接收到的数据
        QByteArray temp = data;
        #if DEBUG_4G
            qDebug() << "4G Recv:" << temp;
        #endif
        QList<QByteArray> dataItems = temp.split('\n');
        
        // 遍历并处理每个数据项
        for(int i = 0; i < dataItems.size(); i++)
        {
            if(!dataItems.at(i).isEmpty())
            {
                parse4gData(dataItems.at(i));
            }
        }
    }
    catch (std::exception &e)
    {
        //qDebug() << "Exception in processPendingData: " << e.what();
    } 
    catch (...)
    {
        //qDebug() << "Unknown exception in processPendingData.";
    }
}
void MyModBus::parse4gData(QByteArray temp)
{
    if(temp.isEmpty() || temp == "\r")
    {
        return;
    }
    QString msg = QString::fromUtf8(temp);
    //qDebug()<<msg;
    //QStringList lst =msg.split("\r");
    //for(int i = 0; i< lst.length(); i++)
    {
//        if(msg.isEmpty())
//        {
//            continue;
//        }
        if(msg.contains("+CPIN"))
        {
            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            QStringList temp =msg.split(":");
            if(temp.length()>1)
            {
                if(temp[1].trimmed() == "READY")
                {
                    set4gCPIN(true);
                }
            }
        }
        else if(msg.contains("+QCCID"))
        {

            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            int p1=msg.indexOf(":");
            m_qccid=msg.mid(p1+1).trimmed();
        }
        else if(msg.contains("+CEREG"))
        {
            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            QStringList temp =msg.split(":");
            if(temp.length()>1)
            {
                if(temp[1].trimmed().split(",")[1]=="1"
                    || temp[1].trimmed().split(",")[1]=="5")
                {
                    if(temp[1].trimmed().split(",").length()>1)
                    {
                        set4gCEREG(true);
                    }
                }
            }
        }
        else if(msg.contains("+CCLK:"))
        {
            int p1=msg.indexOf(":");

            QString time_o=msg.mid(p1+1).trimmed();

            int pos = time_o.length()-2;
            time_o = time_o.mid(1,pos);

            QStringList timeLst=time_o.split("+");

            //int hour = timeLst[1].toInt()/4;
            QDateTime dateTime = QDateTime::fromString("20"+timeLst[0], "yyyy/MM/dd,hh:mm:ss");
            //dateTime=dateTime.addSecs(hour*60*60);
            //qDebug()<<"20"+timeLst[0];
            //qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
            correctDateTime(dateTime);
            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            m_getclk = true;
        }
        else if(msg.contains("+QMTOPEN"))
        {
            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            QStringList temp =msg.split(":");

            if(temp.length()>1)
            {
                if(temp[1].trimmed().split(",").length()>1)
                {
                    if(temp[1].trimmed().split(",")[1]=="0")
                    {
                        set4gOpenMqttClient(true);  //哦哦AT命令响应 +QMTPUBEX: <client_idx>,<msgid>,<result>。具体是+QMTPUBEX: 0, 0 (成功是0）
                    }
                }
            }
            m_error_response=true;
        }
        else if(msg.contains("+QMTCONN"))
        {
            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            QStringList temp =msg.split(":");
            if(temp.length()>1)
            {
                    if(temp[1].trimmed().split(",").length()>2)
                    {
                        if(temp[1].trimmed().split(",")[2]=="0")
                        {
                            set4gConnMqttClient(true);
                        }
                    }
            }
            m_error_response=true;
        }
        else if(msg.contains("+QMTSUB"))
        {
            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            QStringList temp =msg.split(":");
            if(temp.length()>1)
            {
                if(temp[1].trimmed().split(",").length()>2)
                {
                        if(temp[1].trimmed().split(",")[2]=="0")
                        {
                            set4gSubSuccess(true);
                        }
                }
            }
            m_error_response=true;
        }
        else if(msg.contains("+QMTRECV"))
        {
            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            //qDebug()<<msg;
            QString lst_tmp=msg;

            if(lst_tmp.contains(":"))
            {
            QString temp = lst_tmp.mid(lst_tmp.indexOf(":"));
            //int pos1 = temp.lastIndexOf(",");
            int pos1=-1;
            for(int i =0;i<3;i++)
            {
                    pos1 = temp.indexOf(",");
                    temp=temp.mid(pos1+1);
            }
            int startIndex= temp.indexOf("\"");
            int endIndex =temp.lastIndexOf("\"");
            //QStringList lst1=temp.split(",", QString::SkipEmptyParts);
            temp = temp.mid(startIndex+1, endIndex-1);
            QJsonParseError parseJsonErr;
            QJsonDocument jsonDoc = QJsonDocument::fromJson(temp.toLocal8Bit().data(), &parseJsonErr);
            if(parseJsonErr.error == QJsonParseError::NoError)
            {
                    if(!jsonDoc.isArray())
                    {
                        QJsonObject rootObj = jsonDoc.object();  // 转化为root对象

                        QJsonValue rootValue = rootObj.value("id");  // 获取指定key对应的value,
                        QString id = rootValue.toString(); // 再将值转换为obj:上一级key对应的值实际为数组对象
                        //qDebug()<<"id:"+id;
                        if(!id.isEmpty())
                        {
                            setSendStatus(id);
                            sendArrRemoveObject(id);
                        }
                    }
                    else
                    {
                        QJsonArray jsonArr =jsonDoc.array();
                        for(int i = 0; i < jsonArr.count(); i++)
                        {
                            if(jsonArr.at(i).type() == QJsonValue::Object)
                            {
                                QJsonObject rootObj = jsonArr.at(i).toObject();  // 转化为root对象

                                QJsonValue rootValue = rootObj.value("id");  // 获取指定key对应的value,
                                QString id = rootValue.toString(); // 再将值转换为obj:上一级key对应的值实际为数组对象
                                qDebug()<<"id:"+id;
                                if(!id.isEmpty())
                                {
                                    setSendStatus(id);
                                    sendArrRemoveObject(id);
                                }
                            }
                        }
                    }
                }
            }
        }
        else if(msg.contains(">"))
        {
            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            m_continueSend = true;
        }
        else if(msg.contains("+CSQ"))
        {
            set4gLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            if(msg.contains(":"))
            {
                    set4gSignal(msg.mid(msg.indexOf(":")+1).simplified());
            }
            m_get4gSignal = true;
        }
        else if(msg.contains("+QGPSGNMEA:"))
        {
            getGPS = true;
            setGpsLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
            //if(msg.contains(":"))
            {
                int pos = msg.indexOf(":");
                QString msg1 = msg.mid(pos + 1);
                if(msg1.contains("$GNGGA"))
                {
                    QStringList list = msg1.split(",");
                    if(list.length() > 11)
                    {
                        if(!list[4].isEmpty())
                        {
                            m_lon_o = list[4].toDouble();
                            m_lon = list[4].toDouble();
                            //m_lon = 10246.973877;
                            int temp_lon = qFloor(m_lon/100);
                            m_lon = temp_lon+(m_lon-temp_lon*100)/60;
                        }
                        m_lon_dir = list[5];

                        if(!list[2].isEmpty())
                        {
                            m_lat_o = list[2].toDouble();
                            m_lat = list[2].toDouble();
                            //m_lat = 2458.928833;
                            int temp_lat = qFloor(m_lat/100);
                            m_lat = temp_lat+(m_lat-temp_lat*100)/60;
                        }
                        m_lat_dir = list[3];
                        if(!list[9].isEmpty())
                        {
                            m_height = list[9].toDouble();
                        }
                        if(!list[10].isEmpty())
                        {
                            m_height_unit = list[10];
                        }
                        //qDebug()<<"";
                    }
                }
            }
        }
        else if(msg.contains("+QMTPUBEX:"))
        {
            pub=true;
        }
        else if(msg.contains("$GNGGA"))
        {
            QStringList list = msg.split(",");
            if(list.length() == 15 && list[0] == "$GNGGA")
            {
                #if DEBUG_GPS
                qDebug() << "receive GPS Data: " << msg;
                #endif
                if(!list[4].isEmpty())
                {
                    m_lon_o = list[4].toDouble();
                    m_lon = list[4].toDouble();
                    int temp_lon = qFloor(m_lon/100);
                    m_lon = temp_lon+(m_lon-temp_lon*100)/60;
                }

                if(!list[5].isEmpty())
                {
                    m_lon_dir = list[5];
                }

                if(!list[2].isEmpty())
                {
                    m_lat_o = list[2].toDouble();
                    m_lat = list[2].toDouble();
                    int temp_lat = qFloor(m_lat/100);
                    m_lat = temp_lat+(m_lat-temp_lat*100)/60;
                }

                if(!list[3].isEmpty())
                {
                    m_lat_dir = list[3];
                }

                if(!list[9].isEmpty())
                {
                    m_height = list[9].toDouble();
                }
                if(!list[10].isEmpty())
                {
                    m_height_unit = list[10];
                }
            }
        }
    }
}
/*
QString MyModBus::sendCommand(QString cmd, bool isRec, int waitInterval)
{
    //QByteArray data  = cmd.toLocal8Bit();  //toUtf8()

    //data  = QByteArray::fromHex(data); //    表示从十六进制数转成字符串。两位变一位

    //uint16_t wcrc = this->ModbusCRC16(data);
//    qDebug()<<"CRC low8:"<<QString("%1").arg(uint8_t(wcrc), 2, 16,QLatin1Char('0')) //不足4位补0
//             <<"CRC high8:"<<QString("%1").arg(uint8_t(wcrc>>8), 2, 16,QLatin1Char('0'));
//    //低位在前，高位在后
//    data.append(char(wcrc));
//    data.append(char(wcrc>>8));
    //qDebug()<<"cmdSend:"<<data.toHex(' ');

    //serialPort4g->setReadBufferSize(recvlen);

    QString data("");
    if(!serialPort4g)
    {
        return data;
    }
    serialPort4g->write(cmd.toLatin1());
    serialPort4g->waitForBytesWritten(1000);

//    //    QThread::msleep(100);
//    if(!isRec)
//    {
//        return data;
//    }
//    QByteArray buff;

//    qDebug()<<"waitForReadyRead before .......";

//    while(serialPort4g->waitForReadyRead(waitInterval))
//    {

//        QElapsedTimer t;
//        t.start();
//        while(t.elapsed()<100) QCoreApplication::processEvents();

//        qDebug()<<"waitForReadyRead after .......";

//        buff.append(serialPort4g->readAll());
//        //qDebug()<<"buff:"<<buff.toHex(' ');

//        if(buff.isEmpty())
//        {
//            qDebug()<<"buff is null !!!!!!!!";
//        }

//    }

//    if(buff.isEmpty())
//    {
//        qDebug()<<"buff is null  timeout !!!!!!!!";
//    }
//    data = QString::fromUtf8(buff);
    return data;
}*/

void MyModBus::sendCommand(QString cmd)
{
    if((!serialPort4g)||(!m_4gConnStatus))
    {
        return;
    }
//mutex.lock();
    #if DEBUG_4G
        if (cmd != "\r\n")
        {
            qDebug()<<"4G Send:" << cmd;
        }
    #endif
    serialPort4g->write(cmd.toLatin1());
    //serialPort4g->waitForBytesWritten(1000);
    serialPort4g->flush();
    serialPort4g->waitForBytesWritten(50);
//mutex.unlock();
}

void MyModBus::sendGPSCommand(QByteArray data)
{
if((!serialPort4g)||(!m_4gConnStatus))
    {
        return;
    }
    #if DEBUG_GPS
    if (data != "\r\n")
    {
        qDebug()<<"GPS Send:" << data.toHex(' ');
    }
    #endif
//mutex.lock();
    serialPort4g->write(data);
    //serialPort4g->waitForBytesWritten(1000);
    serialPort4g->flush();
    serialPort4g->waitForBytesWritten(50);
//mutex.unlock();
}

void MyModBus::slotReadPreValue14()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            m_preValue14= byteArrayToInt(arry);
            emit preValue14Changed(m_preValue14);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreCondition4()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preCondition4 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preCondition4Changed(m_preCondition4);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}

void MyModBus::slotReadPreMinDuration4()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preMinDuration4 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preMinDuration4Changed(m_preMinDuration4);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}
void MyModBus::slotReadPreIsStable4()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 1)
        {
            m_preIsStable4 =unit.value(0);
            //QString temp = QString::number(unit.value(1), 16)+QString::number(unit.value(0), 16);
            //m_devDate="20"+temp.mid(0,2)+"-"+temp.mid(2,2)+"-"+temp.mid(4,2);
            emit preIsStable4Changed(m_preIsStable4);
        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
    delete reply;
    reply = nullptr;
}
int MyModBus::byteArrayToInt(QByteArray arr,  Endian endian)
{
//    if (arr.size() < 4)
//        return 0;

    int res = 0;

    // 小端模式
    if (endian == LittileEndian)
    {
        res = arr.at(0) & 0x000000FF;
        res |= (arr.at(1) << 8) & 0x0000FF00;
        res |= (arr.at(2) << 16) & 0x00FF0000;
        res |= (arr.at(3) << 24) & 0xFF000000;
    }

    // 大端模式
    else if (endian == BigEndian)
    {
        res = (arr.at(0) << 24) & 0xFF000000;
        res |= (arr.at(1) << 16) & 0x00FF0000;
        res |= arr.at(2) << 8 & 0x0000FF00;
        res |= arr.at(3) & 0x000000FF;
    }
    return res;
}

void MyModBus::collectData()
{
    while(!isClosed)
    {
        getWeight();
        collectData0();
        getCurrent0();
        refreshWeight();
        //emit weightChanged(weight());
        QThread::msleep(m_collectTime);
    }
}

void MyModBus::readWeight(QModbusReply *reply, int i)
{
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 24)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            int _weight= byteArrayToInt(arry);
            uchar arry0_ = (unit.value(22) & 0xFF00)>>8;
            uchar arry1_ = (unit.value(22) & 0x00FF);
            uchar arry2_ = (unit.value(23) & 0xFF00)>>8;
            uchar arry3_ = (unit.value(23) & 0x00FF);
            QByteArray arry_;
            arry_.resize(4);
            arry_[0] = arry0_;
            arry_[1] = arry1_;
            arry_[2] = arry2_;
            arry_[3] = arry3_;
            //+ arry1 + arry2 + arry3;
            int voltage= byteArrayToInt(arry_);

            int _decimal;
            switch(i)
            {
            case 0:
                    _decimal = m_decimalPlaces0;
                    m_voltage0_=voltage;
                    m_voltage0 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    emit voltage0Changed(m_voltage0);
                    if(m_weight.contains(QString::number(i)))
                    {
                        m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    }
                    else
                    {
                        m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                    }
                    m_stable0=unit.value(2)&1;
                    m_normal0=(unit.value(2)>>1)&1;
                    m_zero0=(unit.value(2)>>2)&1;
                    m_positive0=(unit.value(2)>>3)&1;
                    break;
            case 1:
                    _decimal = m_decimalPlaces1;
                    m_voltage1_=voltage;
                    m_voltage1 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    emit voltage1Changed(m_voltage1);
                    if(m_weight.contains(QString::number(i)))
                    {
                        m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    }
                    else
                    {
                        m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                    }
                    m_stable1=unit.value(2)&1;
                    m_normal1=(unit.value(2)>>1)&1;
                    m_zero1=(unit.value(2)>>2)&1;
                    m_positive1=(unit.value(2)>>3)&1;
                    break;
            case 2:
                    _decimal = m_decimalPlaces2;
                    m_voltage2_=voltage;
                    m_voltage2 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    emit voltage2Changed(m_voltage2);
                    if(m_weight.contains(QString::number(i)))
                    {
                        m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    }
                    else
                    {
                        m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                    }
                    m_stable2=unit.value(2)&1;
                    m_normal2=(unit.value(2)>>1)&1;
                    m_zero2=(unit.value(2)>>2)&1;
                    m_positive2=(unit.value(2)>>3)&1;
                    break;
            case 3:
                    _decimal = m_decimalPlaces3;
                    m_voltage3_=voltage;
                    m_voltage3 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    emit voltage3Changed(m_voltage3);

                    if(m_weight.contains(QString::number(i)))
                    {
                        m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    }
                    else
                    {
                        m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                    }
                    m_stable3=unit.value(2)&1;
                    m_normal3=(unit.value(2)>>1)&1;
                    m_zero3=(unit.value(2)>>2)&1;
                    m_positive3=(unit.value(2)>>3)&1;
                    break;
            case 4:
                    _decimal = m_decimalPlaces4;
                    m_voltage4_=voltage;
                    m_voltage4 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    emit voltage4Changed(m_voltage4);

                    if(m_weight.contains(QString::number(i)))
                    {
                        m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    }
                    else
                    {
                        m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                    }
                    m_stable4=unit.value(2)&1;
                    m_normal4=(unit.value(2)>>1)&1;
                    m_zero4=(unit.value(2)>>2)&1;
                    m_positive4=(unit.value(2)>>3)&1;
                    break;
            case 5:

                    _decimal = m_decimalPlaces5;
                    m_voltage5_=voltage;
                    m_voltage5 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    emit voltage5Changed(m_voltage5);

                    if(m_weight.contains(QString::number(i)))
                    {
                        m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    }
                    else
                    {
                        m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                    }
                    m_stable5=unit.value(2)&1;
                    m_normal5=(unit.value(2)>>1)&1;
                    m_zero5=(unit.value(2)>>2)&1;
                    m_positive5=(unit.value(2)>>3)&1;
                    break;
            case 6:
                    _decimal = m_decimalPlaces6;
                    m_voltage6_=voltage;
                    m_voltage6 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    emit voltage6Changed(m_voltage6);

                    if(m_weight.contains(QString::number(i)))
                    {
                        m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    }
                    else
                    {
                        m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                    }
                    m_stable6=unit.value(2)&1;
                    m_normal6=(unit.value(2)>>1)&1;
                    m_zero6=(unit.value(2)>>2)&1;
                    m_positive6=(unit.value(2)>>3)&1;
                    break;
            case 7:
                    _decimal = m_decimalPlaces7;
                    m_voltage7_=voltage;
                    m_voltage7 = QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    emit voltage7Changed(m_voltage7);

                    if(m_weight.contains(QString::number(i)))
                    {
                        m_weight[QString::number(i)]=QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal);
                    }
                    else
                    {
                        m_weight.insert(QString::number(i), QString::number(_weight*qPow(10, -1*_decimal) ,'f' ,_decimal));
                    }
                    m_stable7=unit.value(2)&1;
                    m_normal7=(unit.value(2)>>1)&1;
                    m_zero7=(unit.value(2)>>2)&1;
                    m_positive7=(unit.value(2)>>3)&1;
                    break;
            }
            //m_sensorLastRevTime= QDateTime::currentDateTime();//获取系统当前的时间
            setSensorLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));//格式化时间

        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

    //reply->deleteLater();
}

void MyModBus::readWeight(QModbusReply *reply)
{
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 24)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry0;
            arry[1] = arry1;
            arry[2] = arry2;
            arry[3] = arry3;
            //+ arry1 + arry2 + arry3;
            int _weight= byteArrayToInt(arry);
            uchar arry0_ = (unit.value(22) & 0xFF00)>>8;
            uchar arry1_ = (unit.value(22) & 0x00FF);
            uchar arry2_ = (unit.value(23) & 0xFF00)>>8;
            uchar arry3_ = (unit.value(23) & 0x00FF);
            QByteArray arry_;
            arry_.resize(4);
            arry_[0] = arry0_;
            arry_[1] = arry1_;
            arry_[2] = arry2_;
            arry_[3] = arry3_;
            //+ arry1 + arry2 + arry3;
            int voltage= byteArrayToInt(arry_);
            m_voltage = QString::number(voltage);
            //m_weight_new = QString::number((_weight*qPow(10, -1*m_decimalPlaces))- m_zeroWeight1 ,'f' ,m_decimalPlaces);
            m_weight_new = QString::number((_weight*qPow(10, -1*m_decimalPlaces)) ,'f' ,m_decimalPlaces);   //哦哦 获取到的称重值（QString).
            //哦哦 没有将m_weight_new绑定到QML页面。在C++中，有定时器。在QML中，又有定时器，获取m

            m_stable=unit.value(2)&1;
            m_normal=(unit.value(2)>>1)&1;
            m_zero=(unit.value(2)>>2)&1;
            m_positive=(unit.value(2)>>3)&1;

            switch((unit.value(2)>>4)&7)
            {
                case 0:
                    m_batteryLevel = 0;
                    break;
                case 1:
                    m_batteryLevel = 1;
                    break;
                case 3:
                    m_batteryLevel = 2;
                    break;
                case 7:
                    m_batteryLevel = 3;
                    break;
                default:
                    m_batteryLevel = 0;
                    break;
            }
            m_decimalPlaces =unit.value(18);

            setSensorLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));//格式化时间 哦哦 “功能”页面下的“部件状态”.

        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }
}

void MyModBus::readAdvPara(QModbusReply *reply)
{
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 6)
        {
            m_powerAutoZero = unit.value(0);
            m_zeroTraceRange = unit.value(1);
            m_stabilityRange = unit.value(2);
            m_clearRange = unit.value(3);
            m_steadyStateFiltering = unit.value(4);
            m_aDSampleRate = unit.value(5);
            setSensorLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));//格式化时间

        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }
}

bool MyModBus::sendOTACommandQICSGP()
{
    QByteArray buff;
    QString recv = "";
    bool getOK = false;
    QElapsedTimer t;
    QString cmd =QString("AT+QICSGP=1,1,\"%1\",\"\",\"\",1\r\n").arg(m_apn);
    int count=-1;
    while(++count<3 && !getOK)
    {
        sendCommand(cmd);
        t.start();
        do
        {
            QElapsedTimer t1;
            t1.start();
            while(t1.elapsed()<200) QCoreApplication::processEvents();
            buff = serialPort4g->readAll();
            if(buff.length()>0)
            {
                    recv = QString::fromUtf8(buff);
                    QStringList lst =recv.split("\r\n");
                    for(int i = 0; i< lst.length(); i++)
                    {
                        if(lst[i].toLower().contains("ok"))
                        {
                            getOK = true;
                            break;
                        }
                    }
            }

        }
        while(!getOK && t.elapsed() < 1000);
    }

    return getOK;
}

bool MyModBus::sendOTACommandQIACT()
{
    QString cmd =QString("AT+QIACT=1\r\n");
    QByteArray buff;
    QString recv = "";
    bool getOK = false;

    QElapsedTimer t;
    int count=-1;
    while(++count<3 && !getOK)
    {
        sendCommand(cmd);
        if(count==0)
        {
            t.start();
        }
        else
        {
            t.restart();
        }

        do
        {
            QElapsedTimer t1;
            t1.start();
            while(t1.elapsed()<200) QCoreApplication::processEvents();
            buff = serialPort4g->readAll();
            recv = QString::fromUtf8(buff);
            QStringList lst =recv.split("\r\n");
            for(int i = 0; i< lst.length(); i++)
            {
                    if(lst[i].toLower().contains("ok"))
                    {
                        getOK = true;
                        break;
                    }
            }
        }
        while(!getOK && t.elapsed() < 1000);
    }

    return getOK;
}

bool MyModBus::sendOTACommandQHTTPCFG()
{
    QByteArray buff;
    QString recv = "";
    bool getOK = false;
    QElapsedTimer t;

    QString cmd =QString("AT+QHTTPCFG=\"contextid\",1\r\n");
    int count=-1;
    while(++count<3 && !getOK)
    {
        sendCommand(cmd);
        t.start();
        do
        {
            QElapsedTimer t1;
            t1.start();
            while(t1.elapsed()<200) QCoreApplication::processEvents();
            buff = serialPort4g->readAll();
            recv = QString::fromUtf8(buff);
            QStringList lst =recv.split("\r\n");
            for(int i = 0; i< lst.length(); i++)
            {
                if(lst[i].toLower().contains("ok"))
                {
                        getOK = true;
                        break;
                }
            }
        }
        while(!getOK && t.elapsed()<1000);
    }
//    if(!getOK)
//    {
//        return getOK;
//    }

    cmd =QString("AT+QHTTPCFG=\"responseheader\",0\r\n");
    getOK = false;
    count=-1;
    while(++count<3 && !getOK)
    {
        sendCommand(cmd);
        t.restart();
        do
        {
            QElapsedTimer t1;
            t1.start();
            while(t1.elapsed()<200) QCoreApplication::processEvents();
            buff = serialPort4g->readAll();
            recv = QString::fromUtf8(buff);
            QStringList lst =recv.split("\r\n");
            for(int i = 0; i< lst.length(); i++)
            {
                if(lst[i].toLower().contains("ok"))
                {
                        getOK = true;
                        break;
                }
            }
        }
        while(!getOK && t.elapsed()<1000);
    }

    return getOK;
}

bool MyModBus::sendOTACommandQHTTP()
{
    QString url = QString("%1").arg(m_url.simplified());
    QString api = QString("api/meterUpgrade/checkUpdate?Unique=%1&Version=%2&Model=%3")
                      .arg(m_deviceID)
                      .arg(m_version)
                      .arg(m_deviceType);
    QString fullUrl;
    QElapsedTimer t;
    if(url[url.length()-1]=="/")
    {
        fullUrl = QString("%1%2\r\n")
                      .arg(url)
                      .arg(api);
    }
    else
    {
        fullUrl = QString("%1/%2\r\n")
                      .arg(url)
                      .arg(api);
    }
    int urlLength=fullUrl.length();

    QString cmd =QString("AT+QHTTPURL=%1,80\r\n").arg(urlLength-2);
    QString buff;
    QString recv = "";
    bool getConnect = false;
    int count = -1;
    while(++count<5 && !getConnect)
    {
        sendCommand(cmd);
        t.start();
        do
        {
            QElapsedTimer t1;
            t1.start();
            while(t1.elapsed()<200) QCoreApplication::processEvents();
            recv = QString::fromUtf8(serialPort4g->readAll());
            QStringList lst =recv.split("\r\n");
            for(int i = 0; i< lst.length(); i++)
            {
                if(lst[i].toLower().contains("connect"))
                {
                        getConnect = true;
                        QThread::msleep(10);
                        sendCommand(fullUrl);
                        break;
                }
            }
        }
        while(!getConnect && t.elapsed()<3000);
        if(getConnect)
        {
            break;
        }
    }

    if(!getConnect)
    {
        return getConnect;
    }

    bool http200 = false;

    QThread::msleep(100);
    count = -1;
    while(++count<5 && !http200)
    {

        sendCommand("AT+QHTTPGET=80\r\n");
        t.restart();
        do
        {
            QElapsedTimer t1;
            t1.start();
            while(t1.elapsed()<200) QCoreApplication::processEvents();
            recv = QString::fromLatin1(serialPort4g->readAll());
            if(recv.length()==0){
                QThread::msleep(100);
                continue;
            }
            QStringList lst =recv.split("\r\n");
            qDebug()<<recv;
            for(int i = 0; i< lst.length(); i++)
            {
                if(lst[i].toLower().contains("+qhttpget:"))
                {
                        QStringList lstTmp =lst[i].split(":");
                        if(lstTmp.length()>1)
                        {
                            QStringList lstRes =lstTmp[1].split(",");
                            if(lstRes.length()>1)
                            {
                                        if(lstRes[0].simplified()=="0"&&(lstRes[1].simplified()=="200"))
                                {
                                    http200 = true;
                                    break;
                                }
                            }
                        }
                }
            }
        }
        while(!http200 && t.elapsed()<3000);
        if(http200)
        {
            break;
        }
    }

    if(!http200)
    {
        return http200;
    }

    bool readHttp = false;
    bool startRead=false;
    buff.clear();
    count = -1;
    QThread::msleep(100);
    while(++count<5 && !(readHttp && !startRead)){

        sendCommand("AT+QHTTPREAD=80\r\n");
        t.restart();
        do
        {
            QElapsedTimer t1;
            t1.start();
            while(t1.elapsed()<200) QCoreApplication::processEvents();
            recv = QString::fromUtf8(serialPort4g->readAll());
            QStringList lst =recv.split("\r\n");
            for(int i = 0; i< lst.length(); i++)
            {
                if(lst[i].toLower().contains("ok"))
                {
                    startRead=false;
                }
                if(startRead)
                {
                        buff.append(lst[i]);
                }
                else
                {
                        if(lst[i].toLower().contains("connect"))
                        {
                            startRead = true;
                            readHttp = true;
                        }
                }

            }
        }
        while(!(readHttp && !startRead) && t.elapsed()<3000);
        if(readHttp && !startRead)
        {
            break;
        }
    }
    if(!(readHttp && !startRead))
    {
        return false;
    }
    QString urlHttp;
    QJsonParseError parseJsonErr;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(buff.toLocal8Bit().data(), &parseJsonErr);
    if(parseJsonErr.error == QJsonParseError::NoError)
    {
        QJsonObject rootObj = jsonDoc.object();  // 转化为root对象

        QJsonObject rootValue = rootObj.value("result").toObject();  // 获取指定key对应的value,
        urlHttp = rootValue.value("urlHttp").toString(); // 再将值转换为obj:上一级key对应的值实际为数组对象
    }
    QThread::msleep(100);
    //count =-1;
    //while(++count<5 && !getConnect)
    //{
        cmd =QString("AT+QHTTPURL=%1,80\r\n").arg(urlHttp.length());
        sendCommand(cmd);
        getConnect = false;
        t.restart();
        do
        {
            QElapsedTimer t1;
            t1.start();
            while(t1.elapsed()<200) QCoreApplication::processEvents();
            recv = QString::fromUtf8(serialPort4g->readAll());
            QStringList lst =recv.split("\r\n");
            for(int i = 0; i< lst.length(); i++)
            {
                if(lst[i].toLower().contains("connect"))
                {
                        getConnect = true;
                        urlHttp.append("\r\n");
                        sendCommand(urlHttp);
                        break;
                }
            }
        }
        while(!getConnect && t.elapsed()<3000);
//        if(getConnect)
//        {
//            break;
//        }
    //}

    if(!getConnect)
    {
        return getConnect;
    }
    http200 = false;
    QThread::msleep(200);
    int byteCount=2000;
    QThread::msleep(100);
    //count = -1;
    //while(++count<5 && !http200){
        sendCommand("AT+QHTTPGET=80\r\n");
        t.restart();
        do
        {
            QElapsedTimer t1;
            t1.start();
            while(t1.elapsed()<200) QCoreApplication::processEvents();
            recv = QString::fromUtf8(serialPort4g->readAll());
            if(recv.length()==0)
            {
                continue;
            }
            QStringList lst =recv.split("\r\n");
            qDebug()<<recv;
            for(int i = 0; i< lst.length(); i++)
            {
                if(lst[i].toLower().contains("+qhttpget:"))
                {
                        QStringList lstTmp =lst[i].split(":");
                        if(lstTmp.length()>1)
                        {
                            QStringList lstRes =lstTmp[1].split(",");
                            if(lstRes.length()>2)
                            {
                                if(lstRes[0].simplified()=="0"&&lstRes[1].simplified()=="200")
                                {
                                    http200 = true;
                                    byteCount=lstRes[2].simplified().toInt();
                                    break;
                                }
                            }
                        }
                }
            }
        }
        while(!http200 && t.elapsed()<3000);
    //}
    if(!http200)
    {
        return http200;
    }

    QString path =QString("/usr/Upgrade/ShelfScale.zip");
    //判断指定文件是否存在.也可以用来判断在指定路径下是否有文件和你将要创建的文件重名.
    //存在返回true，不存在返回false
    bool exist = QFile::exists(path);
    if(exist)
    {
        QFile::remove(path);
    }
    QFile file(path);
    //打开文件
    bool isOk = file.open(QIODevice::WriteOnly);
    if(isOk == false)
    {
        return false;
    }
    //创建数据流 与文件相关联
    //往数据流里写数据 就相当于往文件里写数据
    QDataStream data(&file);
//    connect(serialPort4g,SIGNAL(readyRead()),this,SLOT([&data](){

//            }));
    bool readFile = false;
    startRead=false;
    //QByteArray buffer[byteCount];
    //buffer.resize(byteCount);
    int recCount=0;

    QEventLoop loop;
    QTimer run_timer_;

    run_timer_.setSingleShot(true); // 单次触发
    run_timer_.setInterval(300000);
    // 连接定时器超时信号到QEventLoop的quit槽
    QObject::connect(&run_timer_, &QTimer::timeout, &loop, &QEventLoop::quit);
    QMetaObject::Connection m_res = connect(serialPort4g, &QSerialPort::readyRead, this, [&](){
        QByteArray tmpBuf=serialPort4g->readAll();
        QString recv1=QString::fromLocal8Bit(tmpBuf);
        //if(recv.length()>0)
        {
            if(startRead)
            {
                for(int i=0;i<tmpBuf.length();i++)
                {
                    if(recCount < byteCount)
                    {
                        char c = tmpBuf.at(i);
                        data.writeRawData(&c,1);
                        //buffer[recCount++]= &c;
                        ++recCount;
                    }
                    else
                    {
                        startRead = false;
                        loop.quit();
                        break;
                    }
                }
                qDebug()<<recCount;
            }
            else
            {
                if(recv1.startsWith("\r\nCONNECT\r\n"))
                {
                    startRead = true;
                    readFile = true;
                    QString head=QString("\r\nCONNECT\r\n");
                    for(int i=head.length();i<tmpBuf.length();i++)
                    {
                        if(recCount < byteCount)
                        {
                            char c = tmpBuf.at(i);
                            //buffer[recCount]= &c;
                            data.writeRawData(&c,1);
                            ++recCount;
                        }
                    }
                }
            }
        }
        });
    QThread::msleep(100);
    sendCommand("AT+QHTTPREAD=600\r\n");
    run_timer_.start();
    loop.exec(); // 进入事件循环，等待返回值
    disconnect(m_res);

    //关闭文件
    file.close();
    QString command = QString("chmod 777 /usr/Upgrade/ShelfScale.zip");
    system(command.toLatin1().data());
    if(!(readFile && !startRead))
    {
        return false;
    }
    return true;
}

bool MyModBus::sendOTACommandDownload()
{
    QByteArray buff;
    sendCommand("AT+QFDWL=\"ShelfScale.tar\"\r\n");
    bool readFile = false;
    bool startRead=false;

    do
    {
        QString recv = QString::fromUtf8(serialPort4g->readAll());
        QStringList lst =recv.split("\r\n");
        for(int i = 0; i< lst.length(); i++)
        {
            if(lst[i].toLower().contains("ok"))
            {
                    startRead=false;
            }
            if(startRead)
            {
                    buff.append(lst[i].toLatin1());
            }
            else
            {
                    if(lst[i].toLower().contains("connect"))
                    {
                        startRead = true;
                        readFile = true;
                    }
            }

        }
    }
    while(!(readFile && !startRead) && serialPort4g->waitForReadyRead(600000));
    if(!(readFile && !startRead))
    {
        return false;
    }
    return true;
}

bool MyModBus::UnzipOTAPackage()
{
    QString fileName=QString("ShelfScale");
    QString path =QString("/usr/Upgrade/%1").arg(fileName);
    //判断指定文件是否存在.也可以用来判断在指定路径下是否有文件和你将要创建的文件重名.
    //存在返回true，不存在返回false
    bool exist = QFile::exists(path);
    if(exist)
    {
        QFile::remove(path);
    }
    QZipReader reader("/usr/Upgrade/ShelfScale.zip");
    reader.extractAll("/usr/Upgrade");

    QFile file("/usr/Upgrade");
    file.open(QIODevice::WriteOnly);
    file.write(reader.fileData(QString::fromLocal8Bit("%1").arg("/usr/Upgrade")));
    file.close();
    reader.close();
    QString command = QString("chmod 777 /usr/Upgrade/%1").arg(fileName);
    //int res =QProcess::execute(command);
    //qDebug()<<res;
    system(command.toLatin1().data());
    //QProcess::execute(command);
    return true;
}

bool MyModBus::powerMode(bool isOn)
{
    QString path = "/sys/class/gpio/gpio195";
    /* 由于system函数只能用char类型，所以进行了转换 */
    if (!QDir(path).exists()) 
    {
        /* export */
        QString cmd_export = "echo 195 > /sys/class/gpio/export";
        QByteArray cmdby_export = cmd_export.toLatin1();
        char* charCmd_export = cmdby_export.data();
        /* config */
        QString cmd_dir = "echo out >"+ path +"/direction";
        QByteArray cmdby_dir = cmd_dir.toLatin1();
        char* charCmd_dir = cmdby_dir.data();
        /* 导出GPIO */
        system(charCmd_export);
        /* 设置GPIO的输入输出状态 */
        system(charCmd_dir);
    }
    if(isOn)
    {
        /* 开 */
        QString cmd_on = "echo 1 >"+ path +"/value";
        QByteArray cmdby_on = cmd_on.toLatin1();
        char* charCmd_on = cmdby_on.data();
        system(charCmd_on);
    }
    else
    {
        /* 关 */
        QString cmd_off = "echo 0 >"+ path +"/value";
        QByteArray cmdby_off = cmd_off.toLatin1();
        char* charCmd_off = cmdby_off.data();
        system(charCmd_off);
    }
    return true;
}

bool MyModBus::switchToGPS(bool isOn)
{
    QString path = "/sys/class/gpio/gpio197";
    /* 由于system函数只能用char类型，所以进行了转换 */
    /* export */
    if (!QDir(path).exists()) 
    {
        QString cmd_export = "echo 197 > /sys/class/gpio/export";
        QByteArray cmdby_export = cmd_export.toLatin1();
        char* charCmd_export = cmdby_export.data();
        /* config */
        QString cmd_dir = "echo out >"+ path +"/direction";
        QByteArray cmdby_dir = cmd_dir.toLatin1();
        char* charCmd_dir = cmdby_dir.data();
        /* 导出GPIO */
        system(charCmd_export);
        /* 设置GPIO的输入输出状态 */
        system(charCmd_dir);
    }
    if(isOn)
    {
        /* 开 */
        QString cmd_on = "echo 1 >"+ path +"/value";
        QByteArray cmdby_on = cmd_on.toLatin1();
        char* charCmd_on = cmdby_on.data();
        system(charCmd_on);
    }
    else
    {
        /* 关 */
        QString cmd_off = "echo 0 >"+ path +"/value";
        QByteArray cmdby_off = cmd_off.toLatin1();
        char* charCmd_off = cmdby_off.data();
        system(charCmd_off);
    }
    return true;
}

bool MyModBus::restart4g(bool isRestart)
{
    QString path = "/sys/class/gpio/gpio196";
    /* 由于system函数只能用char类型，所以进行了转换 */
    if (!QDir(path).exists()) 
    {
        /* export */
        QString cmd_export = "echo 196 > /sys/class/gpio/export";
        QByteArray cmdby_export = cmd_export.toLatin1();
        char* charCmd_export = cmdby_export.data();
        /* config */
        QString cmd_dir = "echo out >"+ path +"/direction";
        QByteArray cmdby_dir = cmd_dir.toLatin1();
        char* charCmd_dir = cmdby_dir.data();
        /* 导出GPIO */
        system(charCmd_export);
        /* 设置GPIO的输入输出状态 */
        system(charCmd_dir);
    }
    if(isRestart)
    {
        /* 关 */
        QString cmd_off = "echo 0 >"+ path +"/value";
        QByteArray cmdby_off = cmd_off.toLatin1();
        char* charCmd_off = cmdby_off.data();
        /* 开 */
        QString cmd_on = "echo 1 >"+ path +"/value";
        QByteArray cmdby_on = cmd_on.toLatin1();
        char* charCmd_on = cmdby_on.data();
       system(charCmd_off);
       QThread::msleep(1000);
       system(charCmd_on);
    }
    return true;
}

bool MyModBus::setVersionAndDevTime(QString version, QString devTime)
{
    bool result = false;
    if(!m_db.isOpen()){
       m_db.open();
    }
    QString queryser= QString("UPDATE versionTable SET version = '%1', devTime = '%2' WHERE id = 1;")
                           .arg(version)
                           .arg(devTime);
    bool updated = m_query->exec(queryser);
    if(!updated){
       m_query->finish();
       //db.close();
       return result;
    }
    m_query->finish();
    //db.close();
    m_version=version;
    m_devTime=devTime;
    //emit userNameChanged(m_topic);
    result = true;
    return result;
}

bool MyModBus::saveComParas(QString comName, int baudrate, int dataBit, int stopBit, int parity, int type)
{
    bool result = false;
    if(!m_db.isOpen())
    {
       m_db.open();
    }
    QString queryser;
    if(type == 0)
    {
       queryser= QString("UPDATE configTable SET dt45COM = '%1', dt45Baudrate = %2, dt45DataBit = %3, dt45StopBit = %4, dt45Parity = %5 WHERE id = 1;")
                      .arg(comName)
                      .arg(baudrate)
                      .arg(dataBit)
                      .arg(stopBit)
                      .arg(parity);
       m_comName = comName;
       m_baudrate = baudrate;
       m_dataBit = dataBit;
       m_stopBit = stopBit;
       m_parity = parity;
    }
    else
    {
       queryser= QString("UPDATE configTable SET COM4g = '%1', baudrate4g = %2, dataBit4g = %3, stopBit4g = %4, parity4g = %5 WHERE id = 1;")
                      .arg(comName)
                      .arg(baudrate)
                      .arg(dataBit)
                      .arg(stopBit)
                      .arg(parity);
       m_comName4g = comName;
       m_baudrate4g = baudrate;
       m_dataBit4g = dataBit;
       m_stopBit4g = stopBit;
       m_parity4g = parity;
    }
    bool updated = m_query->exec(queryser);
    if(!updated){
       m_query->finish();
       //db.close();
       return result;
    }
    m_query->finish();
    //db.close();
    if(type == 0)
    {
       if(modbusDevice)
       {
            modbusDevice->disconnectDevice();
       }
       connectSerialPort();
    }
    else
    {
       change4gport = true;
       reconnect4g = true;
       #if DEBUG_4G
       qDebug()<<"4G change";
       #endif
    }
    result =true;
    return result;
}

void MyModBus::sumWeights()
{
    double sum = 0;
    for(double weight : m_accumulateWeights)
    {
       sum += weight;
    }
    m_weight_new = QString::number(sum ,'f' ,m_decimalPlaces);
}

void MyModBus::clearAccumulateWeights()
{
    m_accumulateWeights.clear();
    QDateTime dateTime0= QDateTime::currentDateTime();//获取系统当前的时间
    QString str0 = dateTime0.toString("yyyy-MM-dd hh:mm:ss");//格式化时间
    saveWeight(str0, m_weight_new.toDouble(), m_unit, 4, 0);
}

void MyModBus::appendAccumulateWeights(QString weight)
{
    QDateTime dateTime0= QDateTime::currentDateTime();//获取系统当前的时间
    QString str0 = dateTime0.toString("yyyy-MM-dd hh:mm:ss");//格式化时间
    saveWeight(str0, weight.toDouble(), m_unit, 1, 0);
    m_accumulateWeights.append(weight.toDouble());
}

void MyModBus::showAccumulateWeightSum(bool isShown)
{
    if(isShown)
    {
       showSumWeight = true;
       sumWeights();
       QDateTime dateTime0= QDateTime::currentDateTime();//获取系统当前的时间
       QString str0 = dateTime0.toString("yyyy-MM-dd hh:mm:ss");//格式化时间
       saveWeight(str0, m_weight_new.toDouble(), m_unit, 3, 0);
    }
    else
    {
       showSumWeight = false;
       getWeight();
    }

}

bool MyModBus::exportToCsv(QString startTime, QString endTime)
{
//    bool loadUSBKO=loadKernelModule("/usr/lib/usb/usb-storage.ko");
//    if(!loadUSBKO)
//    {
//       return false;
//    }
    QString UDiskPath = "";
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString currentTime = currentDateTime.toString("yyyyMMddhhmmsszzz");
    QString filePath
          = "";
         //= QString("/opt/ShelfScale/bin/ExportFile%1.csv").arg(currentTime);
    foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes())
    {

       if (storage.isValid() && storage.isReady())
       {
            UDiskPath = storage.rootPath();
            if(UDiskPath.contains("media"))
            {
                filePath = QString("%1/ExportFile%2.csv").arg(UDiskPath).arg(currentTime);
            }

       }

    }
    if(filePath.length() == 0)
    {
       return false;
    }
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly))
       return false;

    QTextCodec* codec = QTextCodec::codecForName("UTF-8");   // 使用UTF-8编码

    QStringList header = {tr("日期") , tr("重量"), tr("模式"), tr("状态")};
    QString line0 = header.join(",");
    line0 += "\n";
    QByteArray encodedLine0 = codec->fromUnicode(line0);
    file.write(encodedLine0);

    QString queryser;
    if(startTime.length()>0&&endTime.length()>0){

       queryser= QString("select "
                          "createdTime, weight||weightUnit as strWeight "
                          ",(CASE WHEN scheduled = 1 THEN '%3' WHEN scheduled = 0 THEN '%4' WHEN scheduled = -1 THEN '%5' END) as strScheduled "
                          ",(CASE WHEN mode = 0 THEN '%6' WHEN mode = 1 THEN '%7' WHEN mode = 2 THEN '%8' WHEN mode = 3 THEN '%9' WHEN mode = 4 THEN '%10' WHEN mode = 5 THEN '%11' WHEN mode = 6 THEN '%12' WHEN mode = 7 THEN '%13' END) as strMode "
                          "from "
                          "weightTable where createdTime >= '%1' "
                          "and createdTime <= '%2' order by createdTime;")
                      .arg(startTime)
                      .arg(endTime)
                      .arg(tr("定时"))
                      .arg(tr("自动"))
                      .arg(tr("手动"))
                      .arg(tr("正常"))
                      .arg(tr("累加（手动追加）"))
                      .arg(tr("累加（自动追加）"))
                      .arg(tr("累加（求和）"))
                      .arg(tr("累加（清除内存）"))
                      .arg(tr("进入正常模式"))
                      .arg(tr("进入累加模式"))
                      .arg(tr("累加"));
    }
    else
    {
       queryser= QString("select "
                          "createdTime, weight||weightUnit as strWeight "
                          ",(CASE WHEN scheduled = 1 THEN '%1' WHEN scheduled = 0 THEN '%2' WHEN scheduled = -1 THEN '%3' END) as strScheduled "
                          ",(CASE WHEN mode = 0 THEN '%4' WHEN mode = 1 THEN '%5' WHEN mode = 2 THEN '%6' WHEN mode = 3 THEN '%7' WHEN mode = 4 THEN '%8' WHEN mode = 5 THEN '%9' WHEN mode = 6 THEN '%10' WHEN mode = 7 THEN '%11' END) as strMode  "
                          "from "
                          "weightTable order by createdTime;")
                      .arg(tr("定时"))
                      .arg(tr("自动"))
                      .arg(tr("手动"))
                      .arg(tr("正常"))
                      .arg(tr("累加（手动追加）"))
                      .arg(tr("累加（自动追加）"))
                      .arg(tr("累加（求和）"))
                      .arg(tr("累加（清除内存）"))
                      .arg(tr("进入正常模式"))
                      .arg(tr("进入累加模式"))
                      .arg(tr("累加"));
    }
    //m_query->clear();
    if(!m_db.isOpen())
    {
       m_db.open();
    }
    m_weightDatas.clear();


    m_query->exec(queryser);
    while (m_query->next()) {
       QStringList row = {m_query->value(0).toString(), m_query->value(1).toString(), m_query->value(2).toString(), m_query->value(3).toString()};
       QString line = row.join(",");
       line += "\n";
       QByteArray encodedLine = codec->fromUnicode(line);
       file.write(encodedLine);
    }
    file.flush();
    fsync( file.handle() );
    file.close();
    QThread::msleep(1000);
    //file.close();
    return true;
}

void MyModBus::correctTime(QString currentTime)
{
    QString command = QString("date -s '%1' > /dev/null").arg(currentTime);
    system(command.toLatin1().data());
    system("hwclock --systohc");
}
/*
void MyModBus::loadWeightData()
{
    if(m_currentPage<0)
    {
       m_weightDatas.clear();
       emit weightDatasChanged(m_weightDatas);
       return;
    }
    //m_db.open();
    QString queryser;
    if(m_startTime.length()>0&&m_endTime.length()>0){

       queryser= QString("select "
                          "createdTime, weight||weightUnit as strWeight "
                          ",(CASE WHEN scheduled = 1 THEN '%4' WHEN scheduled = 0 THEN '%5' WHEN scheduled = -1 THEN '%6' END) as strScheduled "
                          ",(CASE WHEN mode = 0 THEN '%7' WHEN mode = 1 THEN '%8' WHEN mode = 2 THEN '%9' WHEN mode = 3 THEN '%10' WHEN mode = 4 THEN '%11' WHEN mode = 5 THEN '%12' WHEN mode = 6 THEN '%13' WHEN mode = 7 THEN '%14' END) as strMode "
                          "from "
                          "weightTable where createdTime >= '%1' "
                          "and createdTime <= '%2' order by createdTime "
                          "limit 8 offset %3;")
                      .arg(m_startTime)
                      .arg(m_endTime)
                      .arg(m_currentPage*8)
                      .arg(tr("定时"))
                      .arg(tr("自动"))
                      .arg(tr("手动"))
                      .arg(tr("正常"))
                      .arg(tr("累加（手动追加）"))
                      .arg(tr("累加（自动追加）"))
                      .arg(tr("累加（求和）"))
                      .arg(tr("累加（清除内存）"))
                      .arg(tr("进入正常模式"))
                      .arg(tr("进入累加模式"))
                      .arg(tr("累加"));
    }
    else
    {
       queryser= QString("select "
                          "createdTime, weight||weightUnit as strWeight "
                          ",(CASE WHEN scheduled = 1 THEN '%2' WHEN scheduled = 0 THEN '%3' WHEN scheduled = -1 THEN '%4' END) as strScheduled "
                          ",(CASE WHEN mode = 0 THEN '%5' WHEN mode = 1 THEN '%6' WHEN mode = 2 THEN '%7' WHEN mode = 3 THEN '%8' WHEN mode = 4 THEN '%9' WHEN mode = 5 THEN '%10' WHEN mode = 6 THEN '%11' WHEN mode = 7 THEN '%12' END) as strMode  "
                          "from "
                          "weightTable order by createdTime "
                          "limit 8 offset %1;")
                      .arg(m_currentPage*8)
                      .arg(tr("定时"))
                      .arg(tr("自动"))
                      .arg(tr("手动"))
                      .arg(tr("正常"))
                      .arg(tr("累加（手动追加）"))
                      .arg(tr("累加（自动追加）"))
                      .arg(tr("累加（求和）"))
                      .arg(tr("累加（清除内存）"))
                      .arg(tr("进入正常模式"))
                      .arg(tr("进入累加模式"))
                      .arg(tr("累加"));
    }
    //m_query->clear();
    if(!m_db.isOpen())
    {
       m_db.open();
    }
    m_weightDatas.clear();


    m_query->exec(queryser);
    while (m_query->next()) {
       QVariantMap row;
       row["createdTime"] = m_query->value(0).toString();
       row["strWeight"] = m_query->value(1).toString();
       row["strMode"] = m_query->value(3).toString();
       row["strScheduled"] = m_query->value(2).toString();
       m_weightDatas.append(row);
    }

    emit weightDatasChanged(m_weightDatas);
}*/
void MyModBus::loadWeightData()
{
    if(m_currentPage<0)
    {
       m_weightDatas.clear();
       emit weightDatasChanged(m_weightDatas);
       return;
    }
    //m_db.open();
    QString queryser;
    if(m_startTime.length()>0&&m_endTime.length()>0){

       queryser= QString("select "
                          "createdTime, weight||weightUnit as strWeight "
                          ",scheduled "
                          ",mode "
                          "from "
                          "weightTable where createdTime >= '%1' "
                          "and createdTime <= '%2' order by createdTime "
                          "limit 8 offset %3;")
                      .arg(m_startTime)
                      .arg(m_endTime)
                      .arg(m_currentPage*8);
    }
    else
    {
       queryser= QString("select "
                          "createdTime, weight||weightUnit as strWeight "
                          ",scheduled "
                          ",mode "
                          "from "
                          "weightTable order by createdTime "
                          "limit 8 offset %1;")
                      .arg(m_currentPage*8);
    }
    //m_query->clear();
    if(!m_db.isOpen())
    {
       m_db.open();
    }
    m_weightDatas.clear();

    m_query->exec(queryser);
    while (m_query->next()) {
        QVariantMap row;
        row["createdTime"] = m_query->value(0).toString();
        switch(m_query->value(2).toInt())
        {
            case 1:
                row["strScheduled"] = tr("定时");
                break;
            case 0:
                row["strScheduled"] = tr("自动");
                break;
            case -1:
                row["strScheduled"] = tr("手动");
                break;
            default:
                row["strScheduled"] = tr("未知");
                break;
        }
        switch (m_query->value(3).toInt())
        {
            case 0:
                row["strMode"] = tr("正常");
                break;
            case 1:
                row["strMode"] = tr("累加（手动追加）");
                break;
            case 2:
                row["strMode"] = tr("累加（自动追加）");
                break;
            case 3:
                row["strMode"] = tr("累加（求和）");
                break;
            case 4:
                row["strMode"] = tr("累加（清除内存）");
                break;
            case 5:
                row["strMode"] = tr("进入正常模式");
                break;
            case 6:
                row["strMode"] = tr("进入累加模式");
                break;
            case 7:
                row["strMode"] = tr("累加");
                break;
            default:
                row["strMode"] = tr("未知");
                break;
        }
        row["strWeight"] = m_query->value(1).toString();
        m_weightDatas.append(row);
    }
    emit weightDatasChanged(m_weightDatas);
}


bool MyModBus::saveClientID(QString clientID, QString deviceType)
{
    //deviceID
    bool result = false;
    if(!m_db.isOpen())
    {
       m_db.open();
    }
    QString queryser;
    queryser= QString("UPDATE mqttTable SET topic = 'sensor/%1/weight/up', clientID = '%1', subTopic = 'sensor/%1/weight/down' WHERE id = 1;")
                   .arg(clientID);
    bool updated = m_query->exec(queryser);
    if(!updated){
       m_query->finish();
       //db.close();
       return result;
    }
    queryser.clear();
    queryser= QString("UPDATE configTable SET deviceID = '%1', deviceType = '%2' WHERE id = 1;")
                   .arg(clientID)
                   .arg(deviceType);

    updated = m_query->exec(queryser);
    if(!updated){
       m_query->finish();
       //db.close();
       return result;
    }
    m_query->finish();
    m_deviceID = clientID;
    m_deviceType = deviceType;
    m_clientID = clientID;
    m_topic = QString("sensor/%1/weight/up").arg(clientID);
    m_subTopic=QString("sensor/%1/weight/down").arg(clientID);

    result =true;
    return result;
}

bool MyModBus::slotReadAdvPara()
{
    bool result = false;
    if(!modbusDevice)
    {
       return result;
    }
    bool replyFinished= false;
    QModbusReply *reply = modbusDevice->sendReadRequest(readRequest(7, 6), m_sensorSlaveID);
    if (reply) {
       if (!reply->isFinished())
       {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
       } else {
            replyFinished=true;
       }
       if(replyFinished)
       {
            readAdvPara(reply);
            result = true;
       }
       //reply->deleteLater();
       delete reply;
       reply = nullptr;
    }
    return result;
}

bool MyModBus::slotSaveEncoderPara(int channel, int direction, int filtering, int interval)
{
    bool result = saveEncoderParaDB(channel, interval, direction, filtering)
       && saveEncoderParaSP(direction, filtering);
    return result;
}
void MyModBus::onTimeOut()
{
    try
    {
       getWeight();
       //collectData0();
       //getCurrent0();
       //refreshWeight();
    }
    catch (std::exception &e) {
       //qDebug() << "Exception caught: " << e.what();
    } catch (...) {
       //qDebug() << "Unknown exception caught.";
    }
}

void MyModBus::onTimeOutEncoder()
{
    try
    {
       getAngle();
    }
    catch (std::exception &e) {
       //qDebug() << "Exception caught: " << e.what();
    } catch (...) {
       //qDebug() << "Unknown exception caught.";
    }
}

QVector<double> MyModBus::Doolittle(int n,double *A,double *b)//n为阶数 A为系数矩阵 b为常数矩阵
{
    double *L = new double[n*n];//开辟L矩阵空间
    double *U = new double[n*n];//开辟U矩阵空间
    double *x = new double[n];//开辟y矩阵空间
    double *y = new double[n];//开辟y矩阵空间
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            *(U + i*n + j) = 0;//暂时全部赋值为0
            if (i==j)
            {
                *(L + i*n + j) = 1;//对角线赋值为1
            }
            else
            {
                *(L + i*n + j) = 0;//其他暂时赋值为0
            }
        }
    }
    for (int k = 0; k < n; k++)//计算u和l矩阵的值
    {
        for (int j = k; j < n; j++)
        {
            *(U + k*n + j) = *(A + k*n + j);//第一行
            for (int r = 0; r < k; r++)//接下来由L的前一列算u的下一行
            {
                *(U + k*n + j) = *(U + k*n + j) - (*(L + k*n + r)*(*(U + r*n + j)));
            }
        }
        for (int i = k+1; i < n; i++)//计算L的列
        {
            *(L + i*n + k) = *(A + i*n + k);
            for (int r = 0; r < k; r++)
            {
                *(L + i*n + k) = *(L + i*n + k) - (*(L + i*n + r)*(*(U + r*n + k)));
            }
            *(L + i*n + k) = *(L + i*n + k) / (*(U + k*n + k));
        }
    }
    for (int i = 0; i < n; i++)//由Ly=b算y
    {
        *(y + i) = *(b + i);
        for (int j = 0; j < i; j++)
        {
            *(y + i) = *(y + i) - *(L + i*n + j)*(*(y + j));

        }
    }
    for (int i = n-1; i >= 0; i--)//由Ux=y算x
    {
        *(x + i) = *(y + i);
        for (int j = i+1; j < n; j++)
        {
            *(y + i) = *(y + i) - *(U + i*n + j)*(*(x + j));
        }
        *(x + i) = *(y + i) / (*(U + i*n + i));
    }
    //cout << "解：\n";//得出解
    //m_factors.clear();
    QVector<double> res(n);
        for (int i = 0; i < n; i++)
    {
        //m_factors.append(*(x + i));
         res[i] = (*(x + i));// = *(x + i);
        //cout <<"x"<<i+1<<"："<< *(x + i) << endl;
    }
    delete[]L;//释放空间
    delete[]U;
    delete[]x;
    delete[]y;
    return res;
}

bool MyModBus::calculateFactor()
{
    m_factors.clear();
    for(int i = 0; i < m_axisCount; i++)
    {
         m_factors.append(1);
    }
    if(m_coefficients.length() == 2 * m_axisCount * m_axisCount
        && m_constants.length() == 2 * m_axisCount)
    {
         double* A0=GetSubList(m_coefficients,0,m_coefficients.length()/2);
         double* A1=GetSubList(m_coefficients,m_coefficients.length()/2,m_coefficients.length());
         double* B0=GetSubList(m_constants,0,m_constants.length()/2);
         double* B1=GetSubList(m_constants,m_constants.length()/2,m_constants.length());
         QVector<double> factor1=Doolittle(m_axisCount, A0, B0);
         QVector<double> factor2=Doolittle(m_axisCount, A1, B1);
         if(factor1.length() == factor2.length()
             && factor1.length() == m_axisCount)
         {
            //m_factors.clear();
            for(int i = 0; i < m_axisCount; i++)
            {
                if(qAbs((factor1.at(i)-factor2.at(i))/factor1.at(i))>0.01*m_calThreshold)
                {
                        m_factors.clear();
                        for(int i = 0; i < 4; i++)
                        {
                        m_factors.append(1);
                        }
                        return false;
                }
                m_factors[i] = ((factor1.at(i)+factor2.at(i))/2);;
            }
            return setFactors();
         }
    }

    return false;
}

void MyModBus::appendMatrixData(double constant)
{
    m_constants.push_back(constant);
    switch(m_axisCount)
    {
        case 0:
            //if(m_weight.length() == 1)
            {
                m_coefficients.push_back(m_weight["0"].toDouble()-m_zeroWeights[0]);
            }
            break;
        case 1:
            //if(m_weight.length() == 2)
            {
               m_coefficients.push_back(m_weight["0"].toDouble()-m_zeroWeights[0]);
            }
            break;
        case 2:
            //if(m_weight.length() == 4)
            {
               m_coefficients.push_back(m_weight["0"].toDouble()-m_zeroWeights[0]);
               m_coefficients.push_back(m_weight["1"].toDouble()-m_zeroWeights[1]);
            }

            break;
        case 3:
            //if(m_weight.length() == 6)
            {
               m_coefficients.push_back(m_weight["0"].toDouble()-m_zeroWeights[0]);
               m_coefficients.push_back(m_weight["1"].toDouble()-m_zeroWeights[1]);
               m_coefficients.push_back(m_weight["2"].toDouble()-m_zeroWeights[2]);
            }

            break;
        case 4:
            //if(m_weight.length() == 8)
            {
               m_coefficients.push_back(m_weight["0"].toDouble()-m_zeroWeights[0]);
               m_coefficients.push_back(m_weight["1"].toDouble()-m_zeroWeights[1]);
               m_coefficients.push_back(m_weight["2"].toDouble()-m_zeroWeights[2]);
               m_coefficients.push_back(m_weight["3"].toDouble()-m_zeroWeights[3]);
            }

            break;
        case 5:
            //if(m_weight.length() == 8)
            {
               m_coefficients.push_back(m_weight["0"].toDouble()-m_zeroWeights[0]);
               m_coefficients.push_back(m_weight["1"].toDouble()-m_zeroWeights[1]);
               m_coefficients.push_back(m_weight["2"].toDouble()-m_zeroWeights[2]);
               m_coefficients.push_back(m_weight["3"].toDouble()-m_zeroWeights[3]);
               m_coefficients.push_back(m_weight["4"].toDouble()-m_zeroWeights[4]);
            }

            break;
        case 6:
            //if(m_weight.length() == 8)
            {
               m_coefficients.push_back(m_weight["0"].toDouble()-m_zeroWeights[0]);
               m_coefficients.push_back(m_weight["1"].toDouble()-m_zeroWeights[1]);
               m_coefficients.push_back(m_weight["2"].toDouble()-m_zeroWeights[2]);
               m_coefficients.push_back(m_weight["3"].toDouble()-m_zeroWeights[3]);
               m_coefficients.push_back(m_weight["4"].toDouble()-m_zeroWeights[4]);
               m_coefficients.push_back(m_weight["5"].toDouble()-m_zeroWeights[5]);
            }

            break;
        }
}

void MyModBus::clearMatrixData()
{
    m_constants.clear();
        m_coefficients.clear();
}

int MyModBus::voltage(int deviceIndex)
{
        if(!modbusDevice)
        {
            return -1;
        }
        if(deviceIndex >= m_slaveIDs.length())
        {
            return -1;
        }
        bool replyFinished=false;
        auto *reply = modbusDevice->sendReadRequest(readRequest(22, 2), m_slaveIDs.at(deviceIndex));
        if (reply) {
            if (!reply->isFinished())
            {
               //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadCurrent0);
               QEventLoop eventLoop;
               //connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
               connect(reply, &QModbusReply::finished,this,[&eventLoop,&replyFinished](){
                   replyFinished = true;
                   eventLoop.quit();
               });
               QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
               eventLoop.exec();
            } else {
               //delete reply;
            }
        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
            return -1;
        }
        if(!replyFinished)
        {
            if(reply){
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
            }
            return -1;
        }
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 2)
            {
               uchar arry0 = (unit.value(0) & 0xFF00)>>8;
               uchar arry1 = (unit.value(0) & 0x00FF);
               uchar arry2 = (unit.value(1) & 0xFF00)>>8;
               uchar arry3 = (unit.value(1) & 0x00FF);
               QByteArray arry;
               arry.resize(4);
               arry[0] = arry0;
               arry[1] = arry1;
               arry[2] = arry2;
               arry[3] = arry3;
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               //+ arry1 + arry2 + arry3;
               return byteArrayToInt(arry);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }

        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return -1;
}

bool MyModBus::zeroCalibration(int deviceIndex)
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        if(deviceIndex >= m_slaveIDs.length())
        {
            return result;
        }
        modbusDevice->setTimeout(6000);
        QModbusDataUnit writeUnit = writeRequest(22,2);
        //QModbusDataUnit::RegisterType table = writeUnit.registerType();
        int weight =1;
        int value0=weight&0x0000ffff;
        int value1=(weight&0xffff0000)>>16;


        writeUnit.setValue(0, value1);
        writeUnit.setValue(1, value0);

        //serverEdit 发生给slave的ID
        auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveIDs.at(deviceIndex));
        if (reply) {
            if (!reply->isFinished()) {
               QEventLoop eventLoop;
               connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
               eventLoop.exec();
            }
            //        else {
            //            // broadcast replies return immediately

            //            reply->deleteLater();
            //        }
        } else {
            qDebug()<<tr("Write error: ") + modbusDevice->errorString();
            return result;
        }


        if (reply->error() == QModbusDevice::ProtocolError) {
            QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
            qDebug()<<errStr;
        } else if (reply->error() != QModbusDevice::NoError) {
            qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).arg(reply->error(), -1, 16);
        }
        else if(reply->error() == QModbusDevice::NoError){
            result = true;
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        modbusDevice->setTimeout(60);
        return result;
}

int MyModBus::getDecimalPlaces(int deviceId)
{
        if(!modbusDevice)
        {
            return -1;
        }
        if(deviceId >= m_slaveIDs.length())
        {
            return -1;
        }
        auto *reply = modbusDevice->sendReadRequest(readRequest(18, 1), m_slaveIDs.at(deviceId));
        if (reply) {
            if (!reply->isFinished())
            {
               QEventLoop eventLoop;
               connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
               QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
               eventLoop.exec();
               //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadDecimalPlaces);
            } else {
               //reply->deleteLater();
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
            return -1;
        }

        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 1)
            {
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               return unit.value(0);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }

        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return -1;
}

int MyModBus::getMinGraduation(int deviceId)
{
        if(!modbusDevice)
        {
            return -1;
        }
        if(deviceId >= m_slaveIDs.length())
        {
            return -1;
        }
        auto *reply = modbusDevice->sendReadRequest(readRequest(19, 1), m_slaveIDs.at(deviceId));
        if (reply) {
            if (!reply->isFinished())
            {
               QEventLoop eventLoop;
               connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
               QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
               eventLoop.exec();
               //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadMinGraduation);
            } else {
               //reply->deleteLater();
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
            return -1;
        }
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 1)
            {
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               return unit.value(0);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }

        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return -1;
}

int MyModBus::getMaxRange(int deviceId)
{
        if(!modbusDevice)
        {
            return -1;
        }
        if(deviceId >= m_slaveIDs.length())
        {
            return -1;
        }
        auto *reply = modbusDevice->sendReadRequest(readRequest(20, 2), m_slaveIDs.at(deviceId));
        if (reply) {
            if (!reply->isFinished())
            {
               QEventLoop eventLoop;
               connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
               QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
               eventLoop.exec();
               //connect(reply, &QModbusReply::finished, this, &MyModBus::slotReadMaxRange);
            } else {
               //reply->deleteLater();
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
            return -1;
        }
        if (reply->error() == QModbusDevice::NoError) {
            const QModbusDataUnit unit = reply->result();
            if(unit.valueCount() == 2)
            {
               uchar arry0 = (unit.value(0) & 0xFF00)>>8;
               uchar arry1 = (unit.value(0) & 0x00FF);
               uchar arry2 = (unit.value(1) & 0xFF00)>>8;
               uchar arry3 = (unit.value(1) & 0x00FF);
               QByteArray arry;
               arry.resize(4);
               arry[0] = arry0;
               arry[1] = arry1;
               arry[2] = arry2;
               arry[3] = arry3;
               //m_maxRange = byteArrayToInt(arry);
               //+ arry1 + arry2 + arry3;
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               return byteArrayToInt(arry);
            }
            else
            {
            }
        } else if (reply->error() == QModbusDevice::ProtocolError) {
            qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->rawResult().exceptionCode(), -1, 16);
        } else {
            qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                        arg(reply->errorString()).
                        arg(reply->error(), -1, 16);
        }

        //reply->deleteLater();
        delete reply;
        reply = nullptr;
        return -1;
}

bool MyModBus::setDecimalPlaces(int decimalPlaces, int deviceId)
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        if(deviceId >= m_slaveIDs.length())
        {
            return result;
        }
        //modbusDevice->setTimeout(200);
        QModbusDataUnit writeUnit = writeRequest(18,1);
        writeUnit.setValue(0, decimalPlaces);

        //for(int i=0 ; i<m_slaveIDs.length();i++)
        {
            //serverEdit 发生给slave的ID
            auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveIDs.at(deviceId));
            if (reply) {
               if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
                eventLoop.exec();
               }
               //        else {
               //            // broadcast replies return immediately

               //            reply->deleteLater();
               //        }
            } else {
               qDebug()<<tr("Write error: ") + modbusDevice->errorString();
               return result;
            }

            if (reply->error() == QModbusDevice::ProtocolError) {
               QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                    .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
               qDebug()<<errStr;
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               return result;
            } else if (reply->error() != QModbusDevice::NoError) {
               qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                           arg(reply->errorString()).arg(reply->error(), -1, 16);
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               return result;
            }
            else if(reply->error() == QModbusDevice::NoError){
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
            }
        }
        result = true;
        //m_decimalPlaces = decimalPlaces;
        switch(deviceId)
        {
            case 0:
                m_decimalPlaces0 = decimalPlaces;
                break;
            case 1:
                m_decimalPlaces1 = decimalPlaces;
                break;
            case 2:
                m_decimalPlaces2 = decimalPlaces;
                break;
            case 3:
                m_decimalPlaces3 = decimalPlaces;
                break;
            case 4:
                m_decimalPlaces4 = decimalPlaces;
                break;
            case 5:
                m_decimalPlaces5 = decimalPlaces;
                break;
            case 6:
                m_decimalPlaces6 = decimalPlaces;
                break;
            case 7:
                m_decimalPlaces7 = decimalPlaces;
                break;
        }
        return result;
}

bool MyModBus::setMinGraduation(int minGraduation, int deviceId)
{
        bool result =false;
        if(!modbusDevice)
        {
            return result;
        }
        if(deviceId >= m_slaveIDs.length())
        {
            return result;
        }
        QModbusDataUnit writeUnit = writeRequest(19,1);
        //QModbusDataUnit::RegisterType table = writeUnit.registerType();

        writeUnit.setValue(0, minGraduation);
        //for(int i=0 ; i<m_slaveIDs.length();i++)
        {
            //serverEdit 发生给slave的ID
            auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveIDs.at(deviceId));
            if (reply) {
               if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
                eventLoop.exec();
               }
               //        else {
               //            // broadcast replies return immediately

               //            reply->deleteLater();
               //        }
            } else {
               qDebug()<<tr("Write error: ") + modbusDevice->errorString();
               return result;
            }

            if (reply->error() == QModbusDevice::ProtocolError) {
               QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                    .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
               qDebug()<<errStr;

               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               return result;
            } else if (reply->error() != QModbusDevice::NoError) {
               qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                           arg(reply->errorString()).arg(reply->error(), -1, 16);

               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               return result;
            }
            else if(reply->error() == QModbusDevice::NoError){
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
            }
        }
        //m_minGraduation = minGraduation;
        result =true;
        return result;
}

bool MyModBus::setMaxRange(int maxRange, int deviceId)
{
        bool result = false;
        if(!modbusDevice)
        {
            return result;
        }
        if(deviceId >= m_slaveIDs.length())
        {
            return result;
        }
        QModbusDataUnit writeUnit = writeRequest(20,2);
        //QModbusDataUnit::RegisterType table = writeUnit.registerType();
        int value0=maxRange&0x0000ffff;
        int value1=(maxRange&0xffff0000)>>16;


        writeUnit.setValue(0, value1);
        writeUnit.setValue(1, value0);


        //for(int i=0 ; i<m_slaveIDs.length();i++)
        {
            //serverEdit 发生给slave的ID
            auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_slaveIDs.at(deviceId));
            if (reply) {
               if (!reply->isFinished()) {
                QEventLoop eventLoop;
                connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
                QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
                eventLoop.exec();
               }
               //        else {
               //            // broadcast replies return immediately

               //            reply->deleteLater();
               //        }
            } else {
               qDebug()<<tr("Write error: ") + modbusDevice->errorString();
               return result;
            }

            if (reply->error() == QModbusDevice::ProtocolError) {
               QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                    .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
               qDebug()<<errStr;
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               return result;
            } else if (reply->error() != QModbusDevice::NoError) {
               qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                           arg(reply->errorString()).arg(reply->error(), -1, 16);
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
               return result;
            }
            else if(reply->error() == QModbusDevice::NoError){
               //reply->deleteLater();
               delete reply;
               reply = nullptr;
            }
        }
        //m_maxRange = maxRange;
        result = true;
        return result;
}

void MyModBus::getCollectData0(int deviceIndex)
{
        if(!modbusDevice)
        {
            return;
        }
        if(deviceIndex >= m_slaveIDs.length())
        {
            return;
        }
        if (auto *reply = modbusDevice->sendReadRequest(readRequest(0, 4, QModbusDataUnit::Coils), m_slaveIDs.at(deviceIndex))) {
            if (!reply->isFinished())
            {
               connect(reply, &QModbusReply::finished, this, [=](){
                   slotReadCollectData_(deviceIndex);
               });
            } else {
               delete reply;
            }

        }
        else
        {
            qDebug()<<tr("Read error: ") + modbusDevice->errorString();
        }
}

bool MyModBus::setZeroValue_()
{

        bool result =false;
        if(!m_db.isOpen())
        {
            m_db.open();
        }
        QString value;
        for(int i = 0; i < m_axisCount; i++)
        {
            if(m_weight.contains(QString::number(i)))
            {
               m_zeroWeights[i]=m_weight[QString::number(i)].toDouble();
               value+=m_weight[QString::number(i)].toString()+"|";
            }
            else
            {
               m_zeroWeights[i]=0;
               value+="0|";
            }

        }

        QString queryser= QString("UPDATE configTable SET zeroWeight = '%1' WHERE id = 1;")
                               .arg(value);
        bool updated = m_query->exec(queryser);
        if(!updated){
            //db.close();
            m_query->finish();
            return result;
        }
        m_query->finish();
        //db.close();
        result = true;
        return result;

}

bool MyModBus::setZeroWeight1(QString weight)
{
        bool result =false;
        if(!m_db.isOpen())
        {
            m_db.open();
        }
        QString value;

        QString queryser= QString("UPDATE configTable SET zeroWeight1 = %1 WHERE id = 1;")
                               .arg(weight.toDouble()+m_zeroWeight1);
        bool updated = m_query->exec(queryser);
        if(!updated){
            //db.close();
            m_query->finish();
            return result;
        }
        m_query->finish();
        //db.close();
        m_zeroWeight1 += weight.toDouble();
        result = true;
        return result;
}

bool MyModBus::resetZeroWeight_()
{
        bool result =false;
        if(!m_db.isOpen())
        {
            m_db.open();
        }
        QString value;

        QString queryser= QString("UPDATE configTable SET zeroWeight1 = %1 WHERE id = 1;")
                               .arg(0);
        bool updated = m_query->exec(queryser);
        if(!updated){
            //db.close();
            m_query->finish();
            return result;
        }
        m_query->finish();
        //db.close();
        m_zeroWeight1 = 0;
        result = true;
        return result;
}

//bool MyModBus::setZeroValue_(float value)
//{
//        //    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//        //    db.setDatabaseName("mydatabase.db");
//        //    if(!db.open())
//        //    {
//        //        return;
//        //    }
//        //    QSqlQuery* query = new QSqlQuery(db);
//        bool result =false;
//        if(!m_db.isOpen())
//        {
//            m_db.open();
//        }
//        QString queryser= QString("UPDATE configTable SET zeroWeight = %1 WHERE id = 1;")
//                               .arg(value);
//        bool updated = m_query->exec(queryser);
//        if(!updated){
//            //db.close();
//            m_query->finish();
//            return result;
//        }
//        m_query->finish();
//        //db.close();
//        m_zeroValue_0 = value;
//        result = true;
//        return result;
//}

int MyModBus::getStable(int deviceIndex)
{
    switch(deviceIndex)
    {
        case 0:
            return m_stable0;
        case 1:
            return m_stable1;
        case 2:
            return m_stable2;
        case 3:
            return m_stable3;
        case 4:
            return m_stable4;
        case 5:
            return m_stable5;
        case 6:
            return m_stable6;
        case 7:
            return m_stable7;
    }
    return m_stable0;
}

int MyModBus::getNormal(int deviceIndex)
{
    switch(deviceIndex)
    {
        case 0:
            return m_normal0;
        case 1:
            return m_normal1;
        case 2:
            return m_normal2;
        case 3:
            return m_normal3;
        case 4:
            return m_normal4;
        case 5:
            return m_normal5;
        case 6:
            return m_normal6;
        case 7:
            return m_normal7;
    }
    return m_normal0;
}

int MyModBus::getZero(int deviceIndex)
{
    switch(deviceIndex)
    {
        case 0:
            return m_zero0;
        case 1:
            return m_zero1;
        case 2:
            return m_zero2;
        case 3:
            return m_zero3;
        case 4:
            return m_zero4;
        case 5:
            return m_zero5;
        case 6:
            return m_zero6;
        case 7:
            return m_zero7;
    }
    return m_zero0;
}

int MyModBus::getPositive(int deviceIndex)
{
    switch(deviceIndex)
    {
        case 0:
            return m_positive0;
        case 1:
            return m_positive1;
        case 2:
            return m_positive2;
        case 3:
            return m_positive3;
        case 4:
            return m_positive4;
        case 5:
            return m_positive5;
        case 6:
            return m_positive6;
        case 7:
            return m_positive7;
    }
    return m_positive0;
}

void MyModBus::getCollectVoltage(int deviceIndex)
{
    if(!modbusDevice)
    {
        return;
    }
    if(deviceIndex >= m_slaveIDs.length())
    {
        return;
    }
    if (auto *reply = modbusDevice->sendReadRequest(readRequest(22, 2), m_slaveIDs.at(deviceIndex))) {
        if (!reply->isFinished())
        {
        connect(reply, &QModbusReply::finished, this, [=](){
            slotReadVoltageData(deviceIndex);
        });
        } else {
        //delete reply;
        }
    }
    else
    {
        qDebug()<<tr("Read error: ") + modbusDevice->errorString();
    }
}

int MyModBus::getVoltageById(int deviceIndex)
{
    switch(deviceIndex)
    {
        case 0:
            return m_voltage0_;
        case 1:
            return m_voltage1_;
        case 2:
            return m_voltage2_;
        case 3:
            return m_voltage3_;
        case 4:
            return m_voltage4_;
        case 5:
            return m_voltage5_;
        case 6:
            return m_voltage6_;
        case 7:
            return m_voltage7_;
    }
    return m_voltage0_;
}

int MyModBus::totalCount(QString startTime, QString endTime)
{
    QString ser;
    if(startTime.length()>0&&endTime.length()>0){
        ser= QString("select "
                        "count(1) "
                        "from "
                        "weightTable where createdTime >= '%1' "
                        "and createdTime <= '%2' order by createdTime;")
                    .arg(startTime)
                    .arg(endTime);
    }
    else
    {
        ser= QString("select "
                        "count(1) "
                        "from "
                        "weightTable order by createdTime;");
    }
    //QSqlQuery* query = new QSqlQuery(QSqlDatabase::database("qt_sql_default_connection"));
    m_query->exec(ser);
    int rowCount = 0;
    if(m_query->next())
    {
        rowCount = qCeil(m_query->value(0).toInt()/8.0) ;
    }
    return rowCount;
}

bool MyModBus::saveOTAPara(QString apn, QString url)
{
                /*
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("mydatabase.db");
    if(!db.open())
    {
        return;
    }
    QSqlQuery* query = new QSqlQuery(db);*/
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE otaTable SET apn = '%1', url = '%2' WHERE id = 1;")
                            .arg(apn)
                            .arg(url);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_apn=apn;
    m_url=url;
    //emit apnChanged(m_apn);
    //emit urlChanged(m_url);
    result = true;
    return result;
}

bool MyModBus::slotOTADownload()
{
    reconnect4g=true;
    disconnect(serialPort4g,SIGNAL(readyRead()),this,SLOT(read4gData()));
    disconnect(serialPort4g,SIGNAL(readyRead()),this,SLOT(readGPSData()));
    bool result =false;
    bool step1 = sendOTACommandQICSGP();
    if(!step1)
    {
    //  return result;
    }
    bool step2 = sendOTACommandQIACT();
    if(!step2)
    {
    //  return result;
    }
    bool step3 = sendOTACommandQHTTPCFG();
    if(!step3)
    {
    //  return result;
    }
    bool step4 = false;
    int count=-1;
    while(++count < 3 && !step4)
    {
        step4 = sendOTACommandQHTTP();
    }
    if(!step4)
    {
        connect(serialPort4g,SIGNAL(readyRead()),this,SLOT(read4gData()));
        reconnect4g=false;
        return result;
    }
    bool step5 = UnzipOTAPackage();
    if(!step5)
    {
        connect(serialPort4g,SIGNAL(readyRead()),this,SLOT(read4gData()));
        reconnect4g=false;
        return result;
    }
    result = true;
    connect(serialPort4g,SIGNAL(readyRead()),this,SLOT(read4gData()));
    reconnect4g=false;
    return result;
}

bool MyModBus::uDiskUpgrade()
{
    QString UDiskPath = "";
    QString file="ShelfScale";
    foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes())
    {
        if (storage.isValid() && storage.isReady())
        {
            UDiskPath = storage.rootPath();
            if(UDiskPath.contains("media"))
            {
                qDebug() << "qstring path:" << UDiskPath;
                QString fileName = QString("%1/%2").arg(UDiskPath).arg(file);
                bool exist = QFile::exists(fileName);
                if(exist)
                {
                    QString path =QString("/usr/Upgrade/%1").arg(file);
                    bool exist1 = QFile::exists(path);
                    if(exist1)
                    {
                        QFile::remove(path);
                    }
                    qDebug() << "path:------"<<fileName;
                    QString newFileName = QString("/usr/Upgrade/%1").arg(file);
                    bool ok = QFile::copy(fileName, newFileName);
                    qDebug() << "isOk" << ok;
                    QString command = QString("chmod 777 /usr/Upgrade/%1").arg(file);
                    system(command.toLatin1().data());
                    //QProcess::execute(command);
                    return true;
                }
            }
        }
    }
    return false;
}

bool MyModBus::slotSwitchToGps(bool isOn)
{
    return switchToGPS(isOn);
}

bool MyModBus::slotRestart4g(bool isRestart)
{
    return restart4g(isRestart);
}

bool MyModBus::slotClearAngle()
{
    bool result =false;
    if(!encoderModbusDevice)
    {
        return result;
    }
    encoderModbusDevice->setTimeout(100);

    int add = RW_REG_POS_ACT_0;
    switch(m_encoderChannel)
    {
    case 0:
        add = RW_REG_POS_ACT_0;
        break;
    case 1:
        add = RW_REG_POS_ACT_1;
        break;
    case 2:
        add = RW_REG_POS_ACT_2;
        break;
    }
    QModbusDataUnit writeUnit = writeRequest(add,2);


    writeUnit.setValue(0, 0);
    writeUnit.setValue(1, 0);

    //serverEdit 发生给slave的ID
    auto *reply = encoderModbusDevice->sendWriteRequest(writeUnit, m_encoderSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            QTimer::singleShot(100, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return result;
    }


    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        result = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    encoderModbusDevice->setTimeout(60);
    return result;
}

bool MyModBus::slotZeroWeight()
{
    bool res = false;
    //modbusDevice->disconnectDevice();
    //pPrinter->Printer_print_receipt(3.2,200,200*3.2);
    //connectSerialPort();

    if(!modbusDevice)
    {
        return res;
    }
    QModbusDataUnit writeUnit = writeRequest(6,1);
    //QModbusDataUnit::RegisterType table = writeUnit.registerType();

    writeUnit.setValue(0, 1);

    //serverEdit 发生给slave的ID
    auto *reply = modbusDevice->sendWriteRequest(writeUnit, m_sensorSlaveID);
    if (reply) {
        if (!reply->isFinished()) {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        }
        //        else {
        //            // broadcast replies return immediately

        //            reply->deleteLater();
        //        }
    } else {
        qDebug()<<tr("Write error: ") + modbusDevice->errorString();
        return res;
    }

    if (reply->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                                .arg(reply->errorString()).arg(reply->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
    } else if (reply->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).arg(reply->error(), -1, 16);
    }
    else if(reply->error() == QModbusDevice::NoError){
        res = true;
    }
    //reply->deleteLater();
    delete reply;
    reply = nullptr;
    return res;
}


double *MyModBus::GetSubList(QVariantList list, int startIndex, int endIndex)
{
    double* res;
    res = new double[endIndex-startIndex];
    for(int i = startIndex; i< endIndex; i++)
    {
         *(res+(i-startIndex)) = list.at(i).toDouble();
    }
    return res;
}

void MyModBus::close()
{
    if(!modbusDevice)
    {
        modbusDevice->disconnectDevice();
        delete modbusDevice;
        modbusDevice = nullptr;
    }
//    timer->stop();
//    delete timer;
//    timer = nullptr;

    isClosed = true;
    if(!serialPort4g)
    {
        serialPort4g->close();
        delete serialPort4g;
        serialPort4g = nullptr;
    }
}

void MyModBus::refreshWeight()
{
    double weight=0;
    if(m_axisCount==0){
        if(!m_weight.contains(QString::number(0)))
        {
               m_weight.insert(QString::number(0), QString::number(0));
        }
        if(m_weight.size()>0){
            weight = m_weight["0"].toFloat()*m_factors[0].toFloat();
        }
    }
    else{
        //if(m_factors.length() == m_axisCount)
        {
            for(int i=0; i<m_axisCount; i++)
            {
                if(!m_weight.contains(QString::number(i)))
                {
                    m_weight.insert(QString::number(i), QString::number(0));
                }
//                if(!m_weight.contains(QString::number(i+m_axisCount)))
//                {
//                    m_weight.insert(QString::number(i+m_axisCount), QString::number(0));
//                }
                weight+=(m_weight[QString::number(i)].toDouble()-m_zeroWeights[i])*m_factors[i].toDouble();
            }
        }
    }

    m_weightData = QString::number(weight - m_zeroWeight1,'f' ,m_decimalPlaces0);
    //emit weightChanged(m_weightData);
}

QString MyModBus::voltage0()
{
    return m_voltage0;
}
QString MyModBus::voltage1()
{
    return m_voltage1;
}
QString MyModBus::voltage2()
{
    return m_voltage2;
}
QString MyModBus::voltage3()
{
    return m_voltage3;
}
QString MyModBus::voltage4()
{
    return m_voltage4;
}
QString MyModBus::voltage5()
{
    return m_voltage5;
}
QString MyModBus::voltage6()
{
    return m_voltage6;
}
QString MyModBus::voltage7()
{
    return m_voltage7;
}

double MyModBus::calThreshold()
{
    return m_calThreshold;
}

bool MyModBus::setCalThreshold(double calThreshold)
{
    /*
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("mydatabase.db");
    if(!db.open())
    {
        return;
    }
    QSqlQuery* query = new QSqlQuery(db);*/
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET calThreshold = %1 WHERE id = 1;")
                           .arg(calThreshold);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_calThreshold=calThreshold;
    emit calThresholdChanged(m_calThreshold);
    result = true;
    return result;
}

int MyModBus::sensorConnStatus()
{
    return m_sensorConnStatus;
}

void MyModBus::setSensorConnStatus(int sensorConnStatus)
{
    m_sensorConnStatus =sensorConnStatus;
    emit sensorConnStatusChanged(m_sensorConnStatus);
}

QString MyModBus::sensorLastRevTime()
{
    return m_sensorLastRevTimeStr;
}

void MyModBus::setSensorLastRevTime(QString sensorLastRevTime)
{
    m_sensorLastRevTimeStr = sensorLastRevTime;
    emit sensorLastRevTimeChanged(m_sensorLastRevTimeStr);
}

bool MyModBus::encoderConnStatus()
{
    return m_encoderConnStatus;
}

void MyModBus::setEncoderConnStatus(bool encoderConnStatus)
{
    m_encoderConnStatus =  encoderConnStatus;
    emit encoderConnStatusChanged(m_encoderConnStatus);
}

QString MyModBus::_4gLastRevTime()
{
    return m_4gLastRevTimeStr;
}

void MyModBus::set4gLastRevTime(QString _4gLastRevTime)
{
    m_4gLastRevTimeStr = _4gLastRevTime;
    emit _4gLastRevTimeChanged(m_4gLastRevTimeStr);
}

QString MyModBus::encoderLastRevTime()
{
    return m_encoderLastRevTime;
}

void MyModBus::setEncoderLastRevTime(QString encoderLastRevTime)
{
    m_encoderLastRevTime = encoderLastRevTime;
    emit encoderLastRevTimeChanged(m_encoderLastRevTime);
}

QString MyModBus::gpsLastRevTime()
{
    return m_gpsLastRevTimeStr;
}

void MyModBus::setGpsLastRevTime(QString gpsLastRevTime)
{
    m_gpsLastRevTimeStr = gpsLastRevTime;
    emit gpsLastRevTimeChanged(m_gpsLastRevTimeStr);
}

bool MyModBus::_4gCPIN()
{
    return m_cpin;
}

void MyModBus::set4gCPIN(bool _4gCPIN)
{
    m_cpin =_4gCPIN;
    _4gCPINChanged(_4gCPIN);
}

int MyModBus::_4gConnStatus()
{
    return m_4gConnStatus;
}

void MyModBus::set4gConnStatus(int _4gConnStatus)
{
    m_4gConnStatus=_4gConnStatus;
    _4gConnStatusChanged(m_4gConnStatus);
}

bool MyModBus::_4gCEREG()
{
    return m_cgreg;
}

void MyModBus::set4gCEREG(bool _4gCEREG)
{
    m_cgreg = _4gCEREG;
    _4gCEREGChanged(m_cgreg);
}

bool MyModBus::_4gOpenMqttClient()
{
    return m_openMqttClient;
}

void MyModBus::set4gOpenMqttClient(bool _4gOpenMqttClient)
{
    m_openMqttClient=_4gOpenMqttClient;
    emit _4gOpenMqttClientChanged(m_openMqttClient);
}

bool MyModBus::_4gConnMqttClient()
{
    return m_connectMqttClient;
}

void MyModBus::set4gConnMqttClient(bool _4gConnMqttClient)
{
    m_connectMqttClient = _4gConnMqttClient;
    emit _4gConnMqttClientChanged(m_connectMqttClient);
}

QString MyModBus::_4gSignal()
{
    return m_4gSignal;
}

void MyModBus::set4gSignal(QString _4gSignal)
{
    m_4gSignal = _4gSignal;
    emit _4gSignalChanged(m_4gSignal);
}

bool MyModBus::_4gSubSuccess()
{
    return m_subSuccess;
}

void MyModBus::set4gSubSuccess(bool _4gSubSuccess)
{
    m_subSuccess = _4gSubSuccess;
    emit _4gSubSuccessChanged(m_subSuccess);
}

QString MyModBus::apn()
{
    return m_apn;
}

bool MyModBus::setApn(QString apn)
{
    /*
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("mydatabase.db");
    if(!db.open())
    {
        return;
    }
    QSqlQuery* query = new QSqlQuery(db);*/
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE otaTable SET apn = '%1' WHERE id = 1;")
                           .arg(apn);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_apn=apn;
    //emit apnChanged(m_apn);
    result = true;
    return result;
}

QString MyModBus::url()
{
    return m_url;
}

bool MyModBus::setUrl(QString url)
{
    /*
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("mydatabase.db");
    if(!db.open())
    {
        return;
    }
    QSqlQuery* query = new QSqlQuery(db);*/
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE otaTable SET url = '%1' WHERE id = 1;")
                           .arg(url);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_url=url;
    //emit urlChanged(m_url);
    result = true;
    return result;
}

QString MyModBus::version()
{
    return m_version;
}

QString MyModBus::devTime()
{
    return m_devTime;
}

int MyModBus::encoderChannel()
{
    return m_encoderChannel;
}

bool MyModBus::setEncoderChannel(int encoderChannel)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET encoderChannel = %1 WHERE id = 1;")
                           .arg(encoderChannel);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_encoderChannel=encoderChannel;
    //emit apnChanged(m_apn);
    result = true;
    return result;
}

int MyModBus::encoderFiltering()
{
    return m_encoderFiltering;
}

bool MyModBus::setEncoderFiltering(int encoderFiltering)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET encoderFiltering = %1 WHERE id = 1;")
                           .arg(encoderFiltering);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_encoderFiltering=encoderFiltering;
    //emit apnChanged(m_apn);
    result = true;
    return result;
}

int MyModBus::encoderDirection()
{
    return m_encoderDirection;
}

bool MyModBus::setEncoderDirection(int encoderDirection)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET encoderDirection = %1 WHERE id = 1;")
                           .arg(encoderDirection);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_encoderDirection=encoderDirection;
    //emit apnChanged(m_apn);
    result = true;
    return result;
}

int MyModBus::encoderInterval()
{
    return m_encoderInterval;
}

bool MyModBus::setEncoderInterval(int encoderInterval)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET encoderInterval = %1 WHERE id = 1;")
                           .arg(encoderInterval);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_encoderInterval=encoderInterval;
    //emit apnChanged(m_apn);
    result = true;
    return result;
}

int MyModBus::pulsePerRev()
{
    return m_pulsePerRev;
}

bool MyModBus::setPulsePerRev(int pulsePerRev)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET pulsePerRev = %1 WHERE id = 1;")
                           .arg(pulsePerRev);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_pulsePerRev=pulsePerRev;
    m_degreePerPulse=360.0/pulsePerRev;
    //emit apnChanged(m_apn);
    result = true;
    return result;
}

int MyModBus::sensorSlaveID()
{
    return m_sensorSlaveID;
}

bool MyModBus::setSensorSlaveID(int sensorSlaveID)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET dt45SlaveId = %1 WHERE id = 1;")
                           .arg(sensorSlaveID);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();

    m_sensorSlaveID=sensorSlaveID;
    //emit sensorSlaveIDChanged(m_sensorSlaveID);
    result = true;
    return result;
}

int MyModBus::encoderSlaveID()
{
    return m_encoderSlaveID;
}

bool MyModBus::setEncoderSlaveID(int encoderSlaveID)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET encoderSlaveId = %1 WHERE id = 1;")
                           .arg(encoderSlaveID);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();

    m_encoderSlaveID=encoderSlaveID;
    emit encoderSlaveIDChanged(m_encoderSlaveID);
    result = true;
    return result;
}

QString MyModBus::angle()
{
    return m_angle;
}

//bool MyModBus::setAngle(QString angle)
//{
//    m_angle = angle;
//    emit angleChanged(m_angle);
//}

QString MyModBus::weightNew()
{
    return m_weight_new;
}

QString MyModBus::voltage()
{
    return m_voltage;
}

int MyModBus::encoderDecimalPlace()
{
    return m_encoderDecimalPlace;
}

bool MyModBus::setEncoderDecimalPlace(int encoderDecimalPlace)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET encoderDecimalPlace = %1 WHERE id = 1;")
                           .arg(encoderDecimalPlace);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_encoderDecimalPlace=encoderDecimalPlace;
    result = true;
    return result;
}

bool MyModBus::loadKernelModule(const QString &modulePath)
{
    QProcess process;
    process.start("insmod", {modulePath});
    if (!process.waitForFinished()) {
        qDebug() << "Failed to load module:" << process.errorString();
        return false;
    }
    return process.exitCode() == 0;
}

void MyModBus::send4gDatas()
{
    while(!isClosed)
    {
        while(arrToSend.count()>0)
        {
            if(!reconnect4g)
            {
                QJsonDocument doc(arrToSend);
                QByteArray jsonData = doc.toJson(); // 序列化到JSON字符串或字节数组
                QJsonDocument copiedDoc = QJsonDocument::fromJson(jsonData); // 反序列化，自动深拷贝
                QJsonArray temp = copiedDoc.array();

                int count = arrToSend.count()>m_mqttInterval?m_mqttInterval:arrToSend.count();
                int groupSize=1;
                for (int i = 0; i < qCeil(count/static_cast<float>(groupSize)); i++)
                {
                    QJsonArray arr;
                    for(int j=0; j < groupSize && (i*groupSize+j)< arrToSend.count();j++)
                    {
                            arr.append(temp.at(i*groupSize+j).toObject());
                    }
                    if(arr.count()==0)
                    {
                            return;
                    }
                    //QString jsonObjStr =QString(QJsonDocument(jsonObj).toJson()).simplified();
                    QJsonDocument jsonDoc = QJsonDocument(arr);
                    QString jsonObjStr =jsonDoc.toJson(QJsonDocument::Compact).simplified();

                    int length = jsonObjStr.length();

                    QElapsedTimer t;
                    t.start();
                    pub = false;
                    //AT+QMTPUBEX=0,0,0,0,"topic/pub",30
                    QString pubCmd = QString("AT+QMTPUBEX=0,0,0,0,\"%1\",%2\r\n")
                                         .arg(m_topic)
                                         .arg(length);
                    m_continueSend=false;
                    sendCommand(pubCmd);
                    //serialPort4g->waitForReadyRead(500);
                    //QThread::msleep(100);
                    qDebug()<<arr.count();
                    while(!m_continueSend && t.elapsed() < 1000)
                    {
                            QCoreApplication::processEvents();
                    }
                    sendCommand(jsonObjStr+"\r\n");
                    qDebug()<<jsonObjStr;
                    //serialPort4g->waitForReadyRead(500);
                    //QThread::msleep(100);
                    while(!pub && t.elapsed() < 15000){
                            QCoreApplication::processEvents();
                    }
                }

            }
        }
    }
}

void MyModBus::getAngle()
{
    if(!encoderModbusDevice)
    {
        return;
    }
    bool replyFinished= false;
    int add = RW_REG_POS_ACT_0;
    switch(m_encoderChannel)
    {
    case 0:
        add = RW_REG_POS_ACT_0;
        break;
    case 1:
        add = RW_REG_POS_ACT_1;
        break;
    case 2:
        add = RW_REG_POS_ACT_2;
        break;
    }

    QModbusReply *reply = encoderModbusDevice->sendReadRequest(readRequest(add, 2), m_encoderSlaveID);
    if (reply) {
        if (!reply->isFinished())
        {
            QEventLoop eventLoop;
            connect(reply, &QModbusReply::finished, this, [&eventLoop, &replyFinished](){
                replyFinished=true;
                eventLoop.quit();
            });
            QTimer::singleShot(180, &eventLoop, &QEventLoop::quit);
            eventLoop.exec();
        } else {
            replyFinished=true;
        }
        if(replyFinished)
        {
            readAngle(reply);
        }
        //reply->deleteLater();
        delete reply;
        reply = nullptr;
    }
}

void MyModBus::readAngle(QModbusReply *reply)
{
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        if(unit.valueCount() == 2)
        {
            uchar arry0 = (unit.value(0) & 0xFF00)>>8;
            uchar arry1 = (unit.value(0) & 0x00FF);
            uchar arry2 = (unit.value(1) & 0xFF00)>>8;
            uchar arry3 = (unit.value(1) & 0x00FF);
            QByteArray arry;
            arry.resize(4);
            arry[0] = arry2;
            arry[1] = arry3;
            arry[2] = arry0;
            arry[3] = arry1;
            //+ arry1 + arry2 + arry3;
            int pulseNum= byteArrayToInt(arry);
            m_angle=QString::number(pulseNum*m_degreePerPulse, 'f', m_encoderDecimalPlace);
            setEncoderLastRevTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));//格式化时间

        }
        else
        {
        }
    } else if (reply->error() == QModbusDevice::ProtocolError) {
        qDebug()<<tr("Read response error: %1 (Mobus exception: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->rawResult().exceptionCode(), -1, 16);
    } else {
        qDebug()<<tr("Read response error: %1 (code: 0x%2)").
                    arg(reply->errorString()).
                    arg(reply->error(), -1, 16);
    }

}

bool MyModBus::saveEncoderParaDB(int channel, int interval, int direction, int filtering)
{
    bool result = false;
    if(!m_db.isOpen())
    {
        m_db.open();
    }
    QString queryser= QString("UPDATE configTable SET encoderChannel = %1, encoderFiltering = %2, encoderDirection = %3, encoderInterval = %4 WHERE id = 1;")
                           .arg(channel)
                           .arg(filtering)
                           .arg(direction)
                           .arg(interval);
    bool updated = m_query->exec(queryser);
    if(!updated){
        m_query->finish();
        //db.close();
        return result;
    }
    m_query->finish();
    m_encoderChannel = channel;
    m_encoderFiltering = filtering;
    m_encoderDirection = direction;
    m_encoderInterval= interval;
    result = true;
    return result;
}

bool MyModBus::saveEncoderParaSP(int direction, int filtering)
{
    bool result =false;
    int add_dir = RW_REG_COUNT_DIR_0;
    int add_filtering = RW_REG_FILTER_LEVEL_0;
    switch(m_encoderChannel)
    {
    case 0:
        add_dir = RW_REG_COUNT_DIR_0;
        add_filtering = RW_REG_FILTER_LEVEL_0;
        break;
    case 1:
        add_dir = RW_REG_COUNT_DIR_1;
        add_filtering = RW_REG_FILTER_LEVEL_1;
        break;
    case 2:
        add_dir = RW_REG_COUNT_DIR_2;
        add_filtering = RW_REG_FILTER_LEVEL_2;
        break;
    }
    if(!encoderModbusDevice)
    {
        return result;
    }
    encoderModbusDevice->setTimeout(100);

    QModbusDataUnit writeUnit_dir = writeRequest(add_dir,1);
    writeUnit_dir.setValue(0, direction);
    auto *reply_dir = encoderModbusDevice->sendWriteRequest(writeUnit_dir, m_encoderSlaveID);
    if (reply_dir) {
        if (!reply_dir->isFinished()) {
            QEventLoop eventLoop;
            connect(reply_dir, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
    } else {
        qDebug()<<tr("Write error: ") + encoderModbusDevice->errorString();
        return result;
    }


    if (reply_dir->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply_dir->errorString()).arg(reply_dir->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
        return result;
    } else if (reply_dir->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply_dir->errorString()).arg(reply_dir->error(), -1, 16);
        return result;
    }
    else if(reply_dir->error() == QModbusDevice::NoError){
    }

    delete reply_dir;
    reply_dir = nullptr;

    QModbusDataUnit writeUnit_filtering = writeRequest(add_filtering,1);
    writeUnit_filtering.setValue(0, filtering);
    auto *reply_filtering = encoderModbusDevice->sendWriteRequest(writeUnit_filtering, m_encoderSlaveID);
    if (reply_filtering) {
        if (!reply_filtering->isFinished()) {
            QEventLoop eventLoop;
            connect(reply_filtering, &QModbusReply::finished,&eventLoop,&QEventLoop::quit);
            eventLoop.exec();
        }
    } else {
        qDebug()<<tr("Write error: ") + encoderModbusDevice->errorString();
        return result;
    }


    if (reply_filtering->error() == QModbusDevice::ProtocolError) {
        QString errStr=tr("Write response error: %1 (Mobus exception: 0x%2)")
                             .arg(reply_filtering->errorString()).arg(reply_filtering->rawResult().exceptionCode(), -1, 16);
        qDebug()<<errStr;
        return result;
    } else if (reply_filtering->error() != QModbusDevice::NoError) {
        qDebug()<<tr("Write response error: %1 (code: 0x%2)").
                    arg(reply_filtering->errorString()).arg(reply_filtering->error(), -1, 16);
        return result;
    }
    else if(reply_filtering->error() == QModbusDevice::NoError){
        result = true;
    }


    delete reply_filtering;
    reply_filtering = nullptr;
    encoderModbusDevice->setTimeout(60);
    return result;
}
